babylon.max.js 2.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200
  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. var SerializationHelper = (function () {
  4816. function SerializationHelper() {
  4817. }
  4818. SerializationHelper.Serialize = function (entity, serializationObject) {
  4819. if (!serializationObject) {
  4820. serializationObject = {};
  4821. }
  4822. // Tags
  4823. if (BABYLON.Tags) {
  4824. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  4825. }
  4826. // Properties
  4827. for (var property in entity.__serializableMembers) {
  4828. var propertyDescriptor = entity.__serializableMembers[property];
  4829. var targetPropertyName = propertyDescriptor.sourceName || property;
  4830. var propertyType = propertyDescriptor.type;
  4831. var sourceProperty = entity[property];
  4832. if (sourceProperty !== undefined && sourceProperty !== null) {
  4833. switch (propertyType) {
  4834. case 0:
  4835. serializationObject[targetPropertyName] = sourceProperty;
  4836. break;
  4837. case 1:
  4838. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4839. break;
  4840. case 2:
  4841. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4842. break;
  4843. case 3:
  4844. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4845. break;
  4846. case 4:
  4847. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4848. break;
  4849. case 5:
  4850. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4851. break;
  4852. case 6:
  4853. serializationObject[targetPropertyName] = sourceProperty.id;
  4854. break;
  4855. case 7:
  4856. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4857. break;
  4858. }
  4859. }
  4860. }
  4861. return serializationObject;
  4862. };
  4863. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  4864. var destination = creationFunction();
  4865. // Tags
  4866. if (BABYLON.Tags) {
  4867. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4868. }
  4869. // Properties
  4870. for (var property in destination.__serializableMembers) {
  4871. var propertyDescriptor = destination.__serializableMembers[property];
  4872. var sourceProperty = source[propertyDescriptor.sourceName || property];
  4873. var propertyType = propertyDescriptor.type;
  4874. if (sourceProperty !== undefined && sourceProperty !== null) {
  4875. switch (propertyType) {
  4876. case 0:
  4877. destination[property] = sourceProperty;
  4878. break;
  4879. case 1:
  4880. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  4881. break;
  4882. case 2:
  4883. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  4884. break;
  4885. case 3:
  4886. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  4887. break;
  4888. case 4:
  4889. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  4890. break;
  4891. case 5:
  4892. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  4893. break;
  4894. case 6:
  4895. destination[property] = scene.getLastMeshByID(sourceProperty);
  4896. break;
  4897. case 7:
  4898. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  4899. break;
  4900. }
  4901. }
  4902. }
  4903. return destination;
  4904. };
  4905. SerializationHelper.Clone = function (creationFunction, source) {
  4906. var destination = creationFunction();
  4907. // Tags
  4908. if (BABYLON.Tags) {
  4909. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4910. }
  4911. // Properties
  4912. for (var property in destination.__serializableMembers) {
  4913. var propertyDescriptor = destination.__serializableMembers[property];
  4914. var sourceProperty = source[property];
  4915. var propertyType = propertyDescriptor.type;
  4916. if (sourceProperty !== undefined && sourceProperty !== null) {
  4917. switch (propertyType) {
  4918. case 0: // Value
  4919. case 6:
  4920. destination[property] = sourceProperty;
  4921. break;
  4922. case 1: // Texture
  4923. case 2: // Color3
  4924. case 3: // FresnelParameters
  4925. case 4: // Vector2
  4926. case 5: // Vector3
  4927. case 7:
  4928. destination[property] = sourceProperty.clone();
  4929. break;
  4930. }
  4931. }
  4932. }
  4933. return destination;
  4934. };
  4935. return SerializationHelper;
  4936. }());
  4937. BABYLON.SerializationHelper = SerializationHelper;
  4938. })(BABYLON || (BABYLON = {}));
  4939. //# sourceMappingURL=babylon.decorators.js.map
  4940. var BABYLON;
  4941. (function (BABYLON) {
  4942. /**
  4943. * A class serves as a medium between the observable and its observers
  4944. */
  4945. var EventState = (function () {
  4946. /**
  4947. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  4948. */
  4949. function EventState(mask, skipNextObservers) {
  4950. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4951. this.initalize(mask, skipNextObservers);
  4952. }
  4953. EventState.prototype.initalize = function (mask, skipNextObservers) {
  4954. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4955. this.mask = mask;
  4956. this.skipNextObservers = skipNextObservers;
  4957. return this;
  4958. };
  4959. return EventState;
  4960. }());
  4961. BABYLON.EventState = EventState;
  4962. /**
  4963. * Represent an Observer registered to a given Observable object.
  4964. */
  4965. var Observer = (function () {
  4966. function Observer(callback, mask) {
  4967. this.callback = callback;
  4968. this.mask = mask;
  4969. }
  4970. return Observer;
  4971. }());
  4972. BABYLON.Observer = Observer;
  4973. /**
  4974. * The Observable class is a simple implementation of the Observable pattern.
  4975. * 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.
  4976. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  4977. * 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).
  4978. * 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.
  4979. */
  4980. var Observable = (function () {
  4981. function Observable() {
  4982. this._observers = new Array();
  4983. this._eventState = new EventState(0);
  4984. }
  4985. /**
  4986. * Create a new Observer with the specified callback
  4987. * @param callback the callback that will be executed for that Observer
  4988. * @param mask the mask used to filter observers
  4989. * @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.
  4990. */
  4991. Observable.prototype.add = function (callback, mask, insertFirst) {
  4992. if (mask === void 0) { mask = -1; }
  4993. if (insertFirst === void 0) { insertFirst = false; }
  4994. if (!callback) {
  4995. return null;
  4996. }
  4997. var observer = new Observer(callback, mask);
  4998. if (insertFirst) {
  4999. this._observers.unshift(observer);
  5000. }
  5001. else {
  5002. this._observers.push(observer);
  5003. }
  5004. return observer;
  5005. };
  5006. /**
  5007. * Remove an Observer from the Observable object
  5008. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5009. */
  5010. Observable.prototype.remove = function (observer) {
  5011. var index = this._observers.indexOf(observer);
  5012. if (index !== -1) {
  5013. this._observers.splice(index, 1);
  5014. return true;
  5015. }
  5016. return false;
  5017. };
  5018. /**
  5019. * Remove a callback from the Observable object
  5020. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5021. */
  5022. Observable.prototype.removeCallback = function (callback) {
  5023. for (var index = 0; index < this._observers.length; index++) {
  5024. if (this._observers[index].callback === callback) {
  5025. this._observers.splice(index, 1);
  5026. return true;
  5027. }
  5028. }
  5029. return false;
  5030. };
  5031. /**
  5032. * Notify all Observers by calling their respective callback with the given data
  5033. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5034. * @param eventData
  5035. * @param mask
  5036. */
  5037. Observable.prototype.notifyObservers = function (eventData, mask) {
  5038. if (mask === void 0) { mask = -1; }
  5039. var state = this._eventState;
  5040. state.mask = mask;
  5041. state.skipNextObservers = false;
  5042. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5043. var obs = _a[_i];
  5044. if (obs.mask & mask) {
  5045. obs.callback(eventData, state);
  5046. }
  5047. if (state.skipNextObservers) {
  5048. return false;
  5049. }
  5050. }
  5051. return true;
  5052. };
  5053. /**
  5054. * return true is the Observable has at least one Observer registered
  5055. */
  5056. Observable.prototype.hasObservers = function () {
  5057. return this._observers.length > 0;
  5058. };
  5059. /**
  5060. * Clear the list of observers
  5061. */
  5062. Observable.prototype.clear = function () {
  5063. this._observers = new Array();
  5064. };
  5065. /**
  5066. * Clone the current observable
  5067. */
  5068. Observable.prototype.clone = function () {
  5069. var result = new Observable();
  5070. result._observers = this._observers.slice(0);
  5071. return result;
  5072. };
  5073. /**
  5074. * Does this observable handles observer registered with a given mask
  5075. * @param {number} trigger - the mask to be tested
  5076. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5077. **/
  5078. Observable.prototype.hasSpecificMask = function (mask) {
  5079. if (mask === void 0) { mask = -1; }
  5080. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5081. var obs = _a[_i];
  5082. if (obs.mask & mask && obs.mask === mask) {
  5083. return true;
  5084. }
  5085. }
  5086. return false;
  5087. };
  5088. return Observable;
  5089. }());
  5090. BABYLON.Observable = Observable;
  5091. })(BABYLON || (BABYLON = {}));
  5092. //# sourceMappingURL=babylon.observable.js.map
  5093. var BABYLON;
  5094. (function (BABYLON) {
  5095. var SmartArray = (function () {
  5096. function SmartArray(capacity) {
  5097. this.length = 0;
  5098. this._duplicateId = 0;
  5099. this.data = new Array(capacity);
  5100. this._id = SmartArray._GlobalId++;
  5101. }
  5102. SmartArray.prototype.push = function (value) {
  5103. this.data[this.length++] = value;
  5104. if (this.length > this.data.length) {
  5105. this.data.length *= 2;
  5106. }
  5107. if (!value.__smartArrayFlags) {
  5108. value.__smartArrayFlags = {};
  5109. }
  5110. value.__smartArrayFlags[this._id] = this._duplicateId;
  5111. };
  5112. SmartArray.prototype.forEach = function (func) {
  5113. for (var index = 0; index < this.length; index++) {
  5114. func(this.data[index]);
  5115. }
  5116. };
  5117. SmartArray.prototype.pushNoDuplicate = function (value) {
  5118. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5119. return false;
  5120. }
  5121. this.push(value);
  5122. return true;
  5123. };
  5124. SmartArray.prototype.sort = function (compareFn) {
  5125. this.data.sort(compareFn);
  5126. };
  5127. SmartArray.prototype.reset = function () {
  5128. this.length = 0;
  5129. this._duplicateId++;
  5130. };
  5131. SmartArray.prototype.dispose = function () {
  5132. this.reset();
  5133. this.data.length = 0;
  5134. };
  5135. SmartArray.prototype.concat = function (array) {
  5136. if (array.length === 0) {
  5137. return;
  5138. }
  5139. if (this.length + array.length > this.data.length) {
  5140. this.data.length = (this.length + array.length) * 2;
  5141. }
  5142. for (var index = 0; index < array.length; index++) {
  5143. this.data[this.length++] = (array.data || array)[index];
  5144. }
  5145. };
  5146. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5147. if (array.length === 0) {
  5148. return;
  5149. }
  5150. if (this.length + array.length > this.data.length) {
  5151. this.data.length = (this.length + array.length) * 2;
  5152. }
  5153. for (var index = 0; index < array.length; index++) {
  5154. var item = (array.data || array)[index];
  5155. this.pushNoDuplicate(item);
  5156. }
  5157. };
  5158. SmartArray.prototype.indexOf = function (value) {
  5159. var position = this.data.indexOf(value);
  5160. if (position >= this.length) {
  5161. return -1;
  5162. }
  5163. return position;
  5164. };
  5165. SmartArray.prototype.contains = function (value) {
  5166. return this.data.indexOf(value) !== -1;
  5167. };
  5168. return SmartArray;
  5169. }());
  5170. // Statics
  5171. SmartArray._GlobalId = 0;
  5172. BABYLON.SmartArray = SmartArray;
  5173. })(BABYLON || (BABYLON = {}));
  5174. //# sourceMappingURL=babylon.smartArray.js.map
  5175. var BABYLON;
  5176. (function (BABYLON) {
  5177. // Screenshots
  5178. var screenshotCanvas;
  5179. var cloneValue = function (source, destinationObject) {
  5180. if (!source)
  5181. return null;
  5182. if (source instanceof BABYLON.Mesh) {
  5183. return null;
  5184. }
  5185. if (source instanceof BABYLON.SubMesh) {
  5186. return source.clone(destinationObject);
  5187. }
  5188. else if (source.clone) {
  5189. return source.clone();
  5190. }
  5191. return null;
  5192. };
  5193. var Tools = (function () {
  5194. function Tools() {
  5195. }
  5196. ;
  5197. /**
  5198. * Interpolates between a and b via alpha
  5199. * @param a The lower value (returned when alpha = 0)
  5200. * @param b The upper value (returned when alpha = 1)
  5201. * @param alpha The interpolation-factor
  5202. * @return The mixed value
  5203. */
  5204. Tools.Mix = function (a, b, alpha) {
  5205. return a * (1 - alpha) + b * alpha;
  5206. };
  5207. Tools.Instantiate = function (className) {
  5208. var arr = className.split(".");
  5209. var fn = (window || this);
  5210. for (var i = 0, len = arr.length; i < len; i++) {
  5211. fn = fn[arr[i]];
  5212. }
  5213. if (typeof fn !== "function") {
  5214. return null;
  5215. }
  5216. return fn;
  5217. };
  5218. Tools.SetImmediate = function (action) {
  5219. if (window.setImmediate) {
  5220. window.setImmediate(action);
  5221. }
  5222. else {
  5223. setTimeout(action, 1);
  5224. }
  5225. };
  5226. Tools.IsExponentOfTwo = function (value) {
  5227. var count = 1;
  5228. do {
  5229. count *= 2;
  5230. } while (count < value);
  5231. return count === value;
  5232. };
  5233. /**
  5234. * Find the next highest power of two.
  5235. * @param x Number to start search from.
  5236. * @return Next highest power of two.
  5237. */
  5238. Tools.CeilingPOT = function (x) {
  5239. x--;
  5240. x |= x >> 1;
  5241. x |= x >> 2;
  5242. x |= x >> 4;
  5243. x |= x >> 8;
  5244. x |= x >> 16;
  5245. x++;
  5246. return x;
  5247. };
  5248. /**
  5249. * Find the next lowest power of two.
  5250. * @param x Number to start search from.
  5251. * @return Next lowest power of two.
  5252. */
  5253. Tools.FloorPOT = function (x) {
  5254. x = x | (x >> 1);
  5255. x = x | (x >> 2);
  5256. x = x | (x >> 4);
  5257. x = x | (x >> 8);
  5258. x = x | (x >> 16);
  5259. return x - (x >> 1);
  5260. };
  5261. /**
  5262. * Find the nearest power of two.
  5263. * @param x Number to start search from.
  5264. * @return Next nearest power of two.
  5265. */
  5266. Tools.NearestPOT = function (x) {
  5267. var c = Tools.CeilingPOT(x);
  5268. var f = Tools.FloorPOT(x);
  5269. return (c - x) > (x - f) ? f : c;
  5270. };
  5271. Tools.GetExponentOfTwo = function (value, max, mode) {
  5272. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5273. var pot;
  5274. switch (mode) {
  5275. case BABYLON.Engine.SCALEMODE_FLOOR:
  5276. pot = Tools.FloorPOT(value);
  5277. break;
  5278. case BABYLON.Engine.SCALEMODE_NEAREST:
  5279. pot = Tools.NearestPOT(value);
  5280. break;
  5281. case BABYLON.Engine.SCALEMODE_CEILING:
  5282. pot = Tools.CeilingPOT(value);
  5283. break;
  5284. }
  5285. return Math.min(pot, max);
  5286. };
  5287. Tools.GetFilename = function (path) {
  5288. var index = path.lastIndexOf("/");
  5289. if (index < 0)
  5290. return path;
  5291. return path.substring(index + 1);
  5292. };
  5293. Tools.GetDOMTextContent = function (element) {
  5294. var result = "";
  5295. var child = element.firstChild;
  5296. while (child) {
  5297. if (child.nodeType === 3) {
  5298. result += child.textContent;
  5299. }
  5300. child = child.nextSibling;
  5301. }
  5302. return result;
  5303. };
  5304. Tools.ToDegrees = function (angle) {
  5305. return angle * 180 / Math.PI;
  5306. };
  5307. Tools.ToRadians = function (angle) {
  5308. return angle * Math.PI / 180;
  5309. };
  5310. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5311. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5312. var output = "";
  5313. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5314. var i = 0;
  5315. var bytes = new Uint8Array(buffer);
  5316. while (i < bytes.length) {
  5317. chr1 = bytes[i++];
  5318. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5319. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5320. enc1 = chr1 >> 2;
  5321. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5322. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5323. enc4 = chr3 & 63;
  5324. if (isNaN(chr2)) {
  5325. enc3 = enc4 = 64;
  5326. }
  5327. else if (isNaN(chr3)) {
  5328. enc4 = 64;
  5329. }
  5330. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5331. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5332. }
  5333. return "data:image/png;base64," + output;
  5334. };
  5335. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5336. if (bias === void 0) { bias = null; }
  5337. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5338. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5339. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5340. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5341. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5342. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5343. }
  5344. if (bias) {
  5345. minimum.x -= minimum.x * bias.x + bias.y;
  5346. minimum.y -= minimum.y * bias.x + bias.y;
  5347. minimum.z -= minimum.z * bias.x + bias.y;
  5348. maximum.x += maximum.x * bias.x + bias.y;
  5349. maximum.y += maximum.y * bias.x + bias.y;
  5350. maximum.z += maximum.z * bias.x + bias.y;
  5351. }
  5352. return {
  5353. minimum: minimum,
  5354. maximum: maximum
  5355. };
  5356. };
  5357. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5358. if (bias === void 0) { bias = null; }
  5359. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5360. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5361. if (!stride) {
  5362. stride = 3;
  5363. }
  5364. for (var index = start; index < start + count; index++) {
  5365. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5366. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5367. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5368. }
  5369. if (bias) {
  5370. minimum.x -= minimum.x * bias.x + bias.y;
  5371. minimum.y -= minimum.y * bias.x + bias.y;
  5372. minimum.z -= minimum.z * bias.x + bias.y;
  5373. maximum.x += maximum.x * bias.x + bias.y;
  5374. maximum.y += maximum.y * bias.x + bias.y;
  5375. maximum.z += maximum.z * bias.x + bias.y;
  5376. }
  5377. return {
  5378. minimum: minimum,
  5379. maximum: maximum
  5380. };
  5381. };
  5382. Tools.Vector2ArrayFeeder = function (array) {
  5383. return function (index) {
  5384. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5385. var length = isFloatArray ? array.length / 2 : array.length;
  5386. if (index >= length) {
  5387. return null;
  5388. }
  5389. if (isFloatArray) {
  5390. var fa = array;
  5391. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5392. }
  5393. var a = array;
  5394. return a[index];
  5395. };
  5396. };
  5397. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5398. if (bias === void 0) { bias = null; }
  5399. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5400. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5401. var i = 0;
  5402. var cur = feeder(i++);
  5403. while (cur) {
  5404. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5405. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5406. cur = feeder(i++);
  5407. }
  5408. if (bias) {
  5409. minimum.x -= minimum.x * bias.x + bias.y;
  5410. minimum.y -= minimum.y * bias.x + bias.y;
  5411. maximum.x += maximum.x * bias.x + bias.y;
  5412. maximum.y += maximum.y * bias.x + bias.y;
  5413. }
  5414. return {
  5415. minimum: minimum,
  5416. maximum: maximum
  5417. };
  5418. };
  5419. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5420. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5421. return undefined;
  5422. return Array.isArray(obj) ? obj : [obj];
  5423. };
  5424. // Misc.
  5425. Tools.GetPointerPrefix = function () {
  5426. var eventPrefix = "pointer";
  5427. // Check if pointer events are supported
  5428. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5429. eventPrefix = "mouse";
  5430. }
  5431. return eventPrefix;
  5432. };
  5433. /**
  5434. * @param func - the function to be called
  5435. * @param requester - the object that will request the next frame. Falls back to window.
  5436. */
  5437. Tools.QueueNewFrame = function (func, requester) {
  5438. if (requester === void 0) { requester = window; }
  5439. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  5440. /*if(requester.isPresenting) {
  5441. return;
  5442. } else*/ if (requester.requestAnimationFrame)
  5443. requester.requestAnimationFrame(func);
  5444. else if (requester.msRequestAnimationFrame)
  5445. requester.msRequestAnimationFrame(func);
  5446. else if (requester.webkitRequestAnimationFrame)
  5447. requester.webkitRequestAnimationFrame(func);
  5448. else if (requester.mozRequestAnimationFrame)
  5449. requester.mozRequestAnimationFrame(func);
  5450. else if (requester.oRequestAnimationFrame)
  5451. requester.oRequestAnimationFrame(func);
  5452. else {
  5453. window.setTimeout(func, 16);
  5454. }
  5455. };
  5456. Tools.RequestFullscreen = function (element) {
  5457. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5458. if (!requestFunction)
  5459. return;
  5460. requestFunction.call(element);
  5461. };
  5462. Tools.ExitFullscreen = function () {
  5463. if (document.exitFullscreen) {
  5464. document.exitFullscreen();
  5465. }
  5466. else if (document.mozCancelFullScreen) {
  5467. document.mozCancelFullScreen();
  5468. }
  5469. else if (document.webkitCancelFullScreen) {
  5470. document.webkitCancelFullScreen();
  5471. }
  5472. else if (document.msCancelFullScreen) {
  5473. document.msCancelFullScreen();
  5474. }
  5475. };
  5476. Tools.SetCorsBehavior = function (url, img) {
  5477. if (Tools.CorsBehavior) {
  5478. switch (typeof (Tools.CorsBehavior)) {
  5479. case "function":
  5480. var result = Tools.CorsBehavior(url);
  5481. if (result) {
  5482. img.crossOrigin = result;
  5483. }
  5484. break;
  5485. case "string":
  5486. default:
  5487. img.crossOrigin = Tools.CorsBehavior;
  5488. break;
  5489. }
  5490. }
  5491. };
  5492. // External files
  5493. Tools.CleanUrl = function (url) {
  5494. url = url.replace(/#/mg, "%23");
  5495. return url;
  5496. };
  5497. Tools.LoadImage = function (url, onload, onerror, database) {
  5498. if (url instanceof ArrayBuffer) {
  5499. url = Tools.EncodeArrayBufferTobase64(url);
  5500. }
  5501. url = Tools.CleanUrl(url);
  5502. var img = new Image();
  5503. if (url.substr(0, 5) !== "data:") {
  5504. Tools.SetCorsBehavior(url, img);
  5505. }
  5506. img.onload = function () {
  5507. onload(img);
  5508. };
  5509. img.onerror = function (err) {
  5510. Tools.Error("Error while trying to load image: " + url);
  5511. if (Tools.UseFallbackTexture) {
  5512. img.src = Tools.fallbackTexture;
  5513. onload(img);
  5514. }
  5515. else {
  5516. onerror();
  5517. }
  5518. };
  5519. var noIndexedDB = function () {
  5520. img.src = url;
  5521. };
  5522. var loadFromIndexedDB = function () {
  5523. database.loadImageFromDB(url, img);
  5524. };
  5525. //ANY database to do!
  5526. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5527. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5528. }
  5529. else {
  5530. if (url.indexOf("file:") !== 0) {
  5531. noIndexedDB();
  5532. }
  5533. else {
  5534. var textureName = url.substring(5).toLowerCase();
  5535. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5536. try {
  5537. var blobURL;
  5538. try {
  5539. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5540. }
  5541. catch (ex) {
  5542. // Chrome doesn't support oneTimeOnly parameter
  5543. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5544. }
  5545. img.src = blobURL;
  5546. }
  5547. catch (e) {
  5548. img.src = null;
  5549. }
  5550. }
  5551. else {
  5552. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5553. img.src = Tools.fallbackTexture;
  5554. }
  5555. }
  5556. }
  5557. return img;
  5558. };
  5559. //ANY
  5560. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5561. url = Tools.CleanUrl(url);
  5562. var noIndexedDB = function () {
  5563. var request = new XMLHttpRequest();
  5564. var loadUrl = Tools.BaseUrl + url;
  5565. request.open('GET', loadUrl, true);
  5566. if (useArrayBuffer) {
  5567. request.responseType = "arraybuffer";
  5568. }
  5569. request.onprogress = progressCallBack;
  5570. request.onreadystatechange = function () {
  5571. // In case of undefined state in some browsers.
  5572. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  5573. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5574. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5575. callback(!useArrayBuffer ? request.responseText : request.response);
  5576. }
  5577. else {
  5578. if (onError) {
  5579. onError(request);
  5580. }
  5581. else {
  5582. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5583. }
  5584. }
  5585. }
  5586. };
  5587. request.send(null);
  5588. };
  5589. var loadFromIndexedDB = function () {
  5590. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5591. };
  5592. if (url.indexOf("file:") !== -1) {
  5593. var fileName = url.substring(5).toLowerCase();
  5594. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5595. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5596. }
  5597. else {
  5598. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5599. }
  5600. }
  5601. else {
  5602. // Caching all files
  5603. if (database && database.enableSceneOffline) {
  5604. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5605. }
  5606. else {
  5607. noIndexedDB();
  5608. }
  5609. }
  5610. };
  5611. /**
  5612. * Load a script (identified by an url). When the url returns, the
  5613. * content of this file is added into a new script element, attached to the DOM (body element)
  5614. */
  5615. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5616. var head = document.getElementsByTagName('head')[0];
  5617. var script = document.createElement('script');
  5618. script.type = 'text/javascript';
  5619. script.src = scriptUrl;
  5620. var self = this;
  5621. script.onload = function () {
  5622. if (onSuccess) {
  5623. onSuccess();
  5624. }
  5625. };
  5626. script.onerror = function () {
  5627. if (onError) {
  5628. onError();
  5629. }
  5630. };
  5631. head.appendChild(script);
  5632. };
  5633. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5634. var reader = new FileReader();
  5635. reader.onload = function (e) {
  5636. //target doesn't have result from ts 1.3
  5637. callback(e.target['result']);
  5638. };
  5639. reader.onprogress = progressCallback;
  5640. reader.readAsDataURL(fileToLoad);
  5641. };
  5642. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5643. var reader = new FileReader();
  5644. reader.onerror = function (e) {
  5645. Tools.Log("Error while reading file: " + fileToLoad.name);
  5646. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5647. };
  5648. reader.onload = function (e) {
  5649. //target doesn't have result from ts 1.3
  5650. callback(e.target['result']);
  5651. };
  5652. reader.onprogress = progressCallBack;
  5653. if (!useArrayBuffer) {
  5654. // Asynchronous read
  5655. reader.readAsText(fileToLoad);
  5656. }
  5657. else {
  5658. reader.readAsArrayBuffer(fileToLoad);
  5659. }
  5660. };
  5661. //returns a downloadable url to a file content.
  5662. Tools.FileAsURL = function (content) {
  5663. var fileBlob = new Blob([content]);
  5664. var url = window.URL || window.webkitURL;
  5665. var link = url.createObjectURL(fileBlob);
  5666. return link;
  5667. };
  5668. // Misc.
  5669. Tools.Format = function (value, decimals) {
  5670. if (decimals === void 0) { decimals = 2; }
  5671. return value.toFixed(decimals);
  5672. };
  5673. Tools.CheckExtends = function (v, min, max) {
  5674. if (v.x < min.x)
  5675. min.x = v.x;
  5676. if (v.y < min.y)
  5677. min.y = v.y;
  5678. if (v.z < min.z)
  5679. min.z = v.z;
  5680. if (v.x > max.x)
  5681. max.x = v.x;
  5682. if (v.y > max.y)
  5683. max.y = v.y;
  5684. if (v.z > max.z)
  5685. max.z = v.z;
  5686. };
  5687. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5688. for (var prop in source) {
  5689. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5690. continue;
  5691. }
  5692. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5693. continue;
  5694. }
  5695. var sourceValue = source[prop];
  5696. var typeOfSourceValue = typeof sourceValue;
  5697. if (typeOfSourceValue === "function") {
  5698. continue;
  5699. }
  5700. if (typeOfSourceValue === "object") {
  5701. if (sourceValue instanceof Array) {
  5702. destination[prop] = [];
  5703. if (sourceValue.length > 0) {
  5704. if (typeof sourceValue[0] == "object") {
  5705. for (var index = 0; index < sourceValue.length; index++) {
  5706. var clonedValue = cloneValue(sourceValue[index], destination);
  5707. if (destination[prop].indexOf(clonedValue) === -1) {
  5708. destination[prop].push(clonedValue);
  5709. }
  5710. }
  5711. }
  5712. else {
  5713. destination[prop] = sourceValue.slice(0);
  5714. }
  5715. }
  5716. }
  5717. else {
  5718. destination[prop] = cloneValue(sourceValue, destination);
  5719. }
  5720. }
  5721. else {
  5722. destination[prop] = sourceValue;
  5723. }
  5724. }
  5725. };
  5726. Tools.IsEmpty = function (obj) {
  5727. for (var i in obj) {
  5728. return false;
  5729. }
  5730. return true;
  5731. };
  5732. Tools.RegisterTopRootEvents = function (events) {
  5733. for (var index = 0; index < events.length; index++) {
  5734. var event = events[index];
  5735. window.addEventListener(event.name, event.handler, false);
  5736. try {
  5737. if (window.parent) {
  5738. window.parent.addEventListener(event.name, event.handler, false);
  5739. }
  5740. }
  5741. catch (e) {
  5742. // Silently fails...
  5743. }
  5744. }
  5745. };
  5746. Tools.UnregisterTopRootEvents = function (events) {
  5747. for (var index = 0; index < events.length; index++) {
  5748. var event = events[index];
  5749. window.removeEventListener(event.name, event.handler);
  5750. try {
  5751. if (window.parent) {
  5752. window.parent.removeEventListener(event.name, event.handler);
  5753. }
  5754. }
  5755. catch (e) {
  5756. // Silently fails...
  5757. }
  5758. }
  5759. };
  5760. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5761. if (mimeType === void 0) { mimeType = "image/png"; }
  5762. // Read the contents of the framebuffer
  5763. var numberOfChannelsByLine = width * 4;
  5764. var halfHeight = height / 2;
  5765. //Reading datas from WebGL
  5766. var data = engine.readPixels(0, 0, width, height);
  5767. //To flip image on Y axis.
  5768. for (var i = 0; i < halfHeight; i++) {
  5769. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5770. var currentCell = j + i * numberOfChannelsByLine;
  5771. var targetLine = height - i - 1;
  5772. var targetCell = j + targetLine * numberOfChannelsByLine;
  5773. var temp = data[currentCell];
  5774. data[currentCell] = data[targetCell];
  5775. data[targetCell] = temp;
  5776. }
  5777. }
  5778. // Create a 2D canvas to store the result
  5779. if (!screenshotCanvas) {
  5780. screenshotCanvas = document.createElement('canvas');
  5781. }
  5782. screenshotCanvas.width = width;
  5783. screenshotCanvas.height = height;
  5784. var context = screenshotCanvas.getContext('2d');
  5785. // Copy the pixels to a 2D canvas
  5786. var imageData = context.createImageData(width, height);
  5787. var castData = (imageData.data);
  5788. castData.set(data);
  5789. context.putImageData(imageData, 0, 0);
  5790. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5791. };
  5792. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5793. if (mimeType === void 0) { mimeType = "image/png"; }
  5794. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5795. if (successCallback) {
  5796. successCallback(base64Image);
  5797. }
  5798. else {
  5799. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5800. if (("download" in document.createElement("a"))) {
  5801. var a = window.document.createElement("a");
  5802. a.href = base64Image;
  5803. var date = new Date();
  5804. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5805. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5806. window.document.body.appendChild(a);
  5807. a.addEventListener("click", function () {
  5808. a.parentElement.removeChild(a);
  5809. });
  5810. a.click();
  5811. //Or opening a new tab with the image if it is not possible to automatically start download.
  5812. }
  5813. else {
  5814. var newWindow = window.open("");
  5815. var img = newWindow.document.createElement("img");
  5816. img.src = base64Image;
  5817. newWindow.document.body.appendChild(img);
  5818. }
  5819. }
  5820. };
  5821. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5822. if (mimeType === void 0) { mimeType = "image/png"; }
  5823. var width;
  5824. var height;
  5825. // If a precision value is specified
  5826. if (size.precision) {
  5827. width = Math.round(engine.getRenderWidth() * size.precision);
  5828. height = Math.round(width / engine.getAspectRatio(camera));
  5829. }
  5830. else if (size.width && size.height) {
  5831. width = size.width;
  5832. height = size.height;
  5833. }
  5834. else if (size.width && !size.height) {
  5835. width = size.width;
  5836. height = Math.round(width / engine.getAspectRatio(camera));
  5837. }
  5838. else if (size.height && !size.width) {
  5839. height = size.height;
  5840. width = Math.round(height * engine.getAspectRatio(camera));
  5841. }
  5842. else if (!isNaN(size)) {
  5843. height = size;
  5844. width = size;
  5845. }
  5846. else {
  5847. Tools.Error("Invalid 'size' parameter !");
  5848. return;
  5849. }
  5850. if (!screenshotCanvas) {
  5851. screenshotCanvas = document.createElement('canvas');
  5852. }
  5853. screenshotCanvas.width = width;
  5854. screenshotCanvas.height = height;
  5855. var renderContext = screenshotCanvas.getContext("2d");
  5856. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  5857. var newWidth = width;
  5858. var newHeight = newWidth / ratio;
  5859. if (newHeight > height) {
  5860. newHeight = height;
  5861. newWidth = newHeight * ratio;
  5862. }
  5863. var offsetX = Math.max(0, width - newWidth) / 2;
  5864. var offsetY = Math.max(0, height - newHeight) / 2;
  5865. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  5866. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5867. };
  5868. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  5869. if (mimeType === void 0) { mimeType = "image/png"; }
  5870. if (samples === void 0) { samples = 1; }
  5871. var width;
  5872. var height;
  5873. //If a precision value is specified
  5874. if (size.precision) {
  5875. width = Math.round(engine.getRenderWidth() * size.precision);
  5876. height = Math.round(width / engine.getAspectRatio(camera));
  5877. size = { width: width, height: height };
  5878. }
  5879. else if (size.width && size.height) {
  5880. width = size.width;
  5881. height = size.height;
  5882. }
  5883. else if (size.width && !size.height) {
  5884. width = size.width;
  5885. height = Math.round(width / engine.getAspectRatio(camera));
  5886. size = { width: width, height: height };
  5887. }
  5888. else if (size.height && !size.width) {
  5889. height = size.height;
  5890. width = Math.round(height * engine.getAspectRatio(camera));
  5891. size = { width: width, height: height };
  5892. }
  5893. else if (!isNaN(size)) {
  5894. height = size;
  5895. width = size;
  5896. }
  5897. else {
  5898. Tools.Error("Invalid 'size' parameter !");
  5899. return;
  5900. }
  5901. var scene = camera.getScene();
  5902. var previousCamera = null;
  5903. if (scene.activeCamera !== camera) {
  5904. previousCamera = scene.activeCamera;
  5905. scene.activeCamera = camera;
  5906. }
  5907. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5908. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  5909. texture.renderList = scene.meshes;
  5910. texture.samples = samples;
  5911. texture.onAfterRenderObservable.add(function () {
  5912. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5913. });
  5914. scene.incrementRenderId();
  5915. scene.resetCachedMaterial();
  5916. texture.render(true);
  5917. texture.dispose();
  5918. if (previousCamera) {
  5919. scene.activeCamera = previousCamera;
  5920. }
  5921. camera.getProjectionMatrix(true); // Force cache refresh;
  5922. };
  5923. // XHR response validator for local file scenario
  5924. Tools.ValidateXHRData = function (xhr, dataType) {
  5925. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5926. if (dataType === void 0) { dataType = 7; }
  5927. try {
  5928. if (dataType & 1) {
  5929. if (xhr.responseText && xhr.responseText.length > 0) {
  5930. return true;
  5931. }
  5932. else if (dataType === 1) {
  5933. return false;
  5934. }
  5935. }
  5936. if (dataType & 2) {
  5937. // Check header width and height since there is no "TGA" magic number
  5938. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5939. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5940. return true;
  5941. }
  5942. else if (dataType === 2) {
  5943. return false;
  5944. }
  5945. }
  5946. if (dataType & 4) {
  5947. // Check for the "DDS" magic number
  5948. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5949. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5950. return true;
  5951. }
  5952. else {
  5953. return false;
  5954. }
  5955. }
  5956. }
  5957. catch (e) {
  5958. // Global protection
  5959. }
  5960. return false;
  5961. };
  5962. /**
  5963. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5964. * Be aware Math.random() could cause collisions, but:
  5965. * "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"
  5966. */
  5967. Tools.RandomId = function () {
  5968. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5969. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5970. return v.toString(16);
  5971. });
  5972. };
  5973. Object.defineProperty(Tools, "NoneLogLevel", {
  5974. get: function () {
  5975. return Tools._NoneLogLevel;
  5976. },
  5977. enumerable: true,
  5978. configurable: true
  5979. });
  5980. Object.defineProperty(Tools, "MessageLogLevel", {
  5981. get: function () {
  5982. return Tools._MessageLogLevel;
  5983. },
  5984. enumerable: true,
  5985. configurable: true
  5986. });
  5987. Object.defineProperty(Tools, "WarningLogLevel", {
  5988. get: function () {
  5989. return Tools._WarningLogLevel;
  5990. },
  5991. enumerable: true,
  5992. configurable: true
  5993. });
  5994. Object.defineProperty(Tools, "ErrorLogLevel", {
  5995. get: function () {
  5996. return Tools._ErrorLogLevel;
  5997. },
  5998. enumerable: true,
  5999. configurable: true
  6000. });
  6001. Object.defineProperty(Tools, "AllLogLevel", {
  6002. get: function () {
  6003. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6004. },
  6005. enumerable: true,
  6006. configurable: true
  6007. });
  6008. Tools._AddLogEntry = function (entry) {
  6009. Tools._LogCache = entry + Tools._LogCache;
  6010. if (Tools.OnNewCacheEntry) {
  6011. Tools.OnNewCacheEntry(entry);
  6012. }
  6013. };
  6014. Tools._FormatMessage = function (message) {
  6015. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6016. var date = new Date();
  6017. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6018. };
  6019. Tools._LogDisabled = function (message) {
  6020. // nothing to do
  6021. };
  6022. Tools._LogEnabled = function (message) {
  6023. var formattedMessage = Tools._FormatMessage(message);
  6024. console.log("BJS - " + formattedMessage);
  6025. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6026. Tools._AddLogEntry(entry);
  6027. };
  6028. Tools._WarnDisabled = function (message) {
  6029. // nothing to do
  6030. };
  6031. Tools._WarnEnabled = function (message) {
  6032. var formattedMessage = Tools._FormatMessage(message);
  6033. console.warn("BJS - " + formattedMessage);
  6034. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6035. Tools._AddLogEntry(entry);
  6036. };
  6037. Tools._ErrorDisabled = function (message) {
  6038. // nothing to do
  6039. };
  6040. Tools._ErrorEnabled = function (message) {
  6041. Tools.errorsCount++;
  6042. var formattedMessage = Tools._FormatMessage(message);
  6043. console.error("BJS - " + formattedMessage);
  6044. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6045. Tools._AddLogEntry(entry);
  6046. };
  6047. Object.defineProperty(Tools, "LogCache", {
  6048. get: function () {
  6049. return Tools._LogCache;
  6050. },
  6051. enumerable: true,
  6052. configurable: true
  6053. });
  6054. Tools.ClearLogCache = function () {
  6055. Tools._LogCache = "";
  6056. Tools.errorsCount = 0;
  6057. };
  6058. Object.defineProperty(Tools, "LogLevels", {
  6059. set: function (level) {
  6060. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6061. Tools.Log = Tools._LogEnabled;
  6062. }
  6063. else {
  6064. Tools.Log = Tools._LogDisabled;
  6065. }
  6066. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6067. Tools.Warn = Tools._WarnEnabled;
  6068. }
  6069. else {
  6070. Tools.Warn = Tools._WarnDisabled;
  6071. }
  6072. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6073. Tools.Error = Tools._ErrorEnabled;
  6074. }
  6075. else {
  6076. Tools.Error = Tools._ErrorDisabled;
  6077. }
  6078. },
  6079. enumerable: true,
  6080. configurable: true
  6081. });
  6082. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6083. get: function () {
  6084. return Tools._PerformanceNoneLogLevel;
  6085. },
  6086. enumerable: true,
  6087. configurable: true
  6088. });
  6089. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6090. get: function () {
  6091. return Tools._PerformanceUserMarkLogLevel;
  6092. },
  6093. enumerable: true,
  6094. configurable: true
  6095. });
  6096. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6097. get: function () {
  6098. return Tools._PerformanceConsoleLogLevel;
  6099. },
  6100. enumerable: true,
  6101. configurable: true
  6102. });
  6103. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6104. set: function (level) {
  6105. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6106. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6107. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6108. return;
  6109. }
  6110. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6111. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6112. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6113. return;
  6114. }
  6115. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6116. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6117. },
  6118. enumerable: true,
  6119. configurable: true
  6120. });
  6121. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6122. };
  6123. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6124. };
  6125. Tools._StartUserMark = function (counterName, condition) {
  6126. if (condition === void 0) { condition = true; }
  6127. if (!condition || !Tools._performance.mark) {
  6128. return;
  6129. }
  6130. Tools._performance.mark(counterName + "-Begin");
  6131. };
  6132. Tools._EndUserMark = function (counterName, condition) {
  6133. if (condition === void 0) { condition = true; }
  6134. if (!condition || !Tools._performance.mark) {
  6135. return;
  6136. }
  6137. Tools._performance.mark(counterName + "-End");
  6138. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6139. };
  6140. Tools._StartPerformanceConsole = function (counterName, condition) {
  6141. if (condition === void 0) { condition = true; }
  6142. if (!condition) {
  6143. return;
  6144. }
  6145. Tools._StartUserMark(counterName, condition);
  6146. if (console.time) {
  6147. console.time(counterName);
  6148. }
  6149. };
  6150. Tools._EndPerformanceConsole = function (counterName, condition) {
  6151. if (condition === void 0) { condition = true; }
  6152. if (!condition) {
  6153. return;
  6154. }
  6155. Tools._EndUserMark(counterName, condition);
  6156. if (console.time) {
  6157. console.timeEnd(counterName);
  6158. }
  6159. };
  6160. Object.defineProperty(Tools, "Now", {
  6161. get: function () {
  6162. if (window.performance && window.performance.now) {
  6163. return window.performance.now();
  6164. }
  6165. return new Date().getTime();
  6166. },
  6167. enumerable: true,
  6168. configurable: true
  6169. });
  6170. /**
  6171. * This method will return the name of the class used to create the instance of the given object.
  6172. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6173. * @param object the object to get the class name from
  6174. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6175. */
  6176. Tools.getClassName = function (object, isType) {
  6177. if (isType === void 0) { isType = false; }
  6178. var name = null;
  6179. if (!isType && object.getClassName) {
  6180. name = object.getClassName();
  6181. }
  6182. else {
  6183. if (object instanceof Object) {
  6184. var classObj = isType ? object : Object.getPrototypeOf(object);
  6185. name = classObj.constructor["__bjsclassName__"];
  6186. }
  6187. if (!name) {
  6188. name = typeof object;
  6189. }
  6190. }
  6191. return name;
  6192. };
  6193. Tools.first = function (array, predicate) {
  6194. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6195. var el = array_1[_i];
  6196. if (predicate(el)) {
  6197. return el;
  6198. }
  6199. }
  6200. };
  6201. /**
  6202. * This method will return the name of the full name of the class, including its owning module (if any).
  6203. * 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).
  6204. * @param object the object to get the class name from
  6205. * @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.
  6206. */
  6207. Tools.getFullClassName = function (object, isType) {
  6208. if (isType === void 0) { isType = false; }
  6209. var className = null;
  6210. var moduleName = null;
  6211. if (!isType && object.getClassName) {
  6212. className = object.getClassName();
  6213. }
  6214. else {
  6215. if (object instanceof Object) {
  6216. var classObj = isType ? object : Object.getPrototypeOf(object);
  6217. className = classObj.constructor["__bjsclassName__"];
  6218. moduleName = classObj.constructor["__bjsmoduleName__"];
  6219. }
  6220. if (!className) {
  6221. className = typeof object;
  6222. }
  6223. }
  6224. if (!className) {
  6225. return null;
  6226. }
  6227. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6228. };
  6229. /**
  6230. * 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.
  6231. * @param array
  6232. */
  6233. Tools.arrayOrStringFeeder = function (array) {
  6234. return function (index) {
  6235. if (index >= array.length) {
  6236. return null;
  6237. }
  6238. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6239. if (val && val.getHashCode) {
  6240. val = val.getHashCode();
  6241. }
  6242. if (typeof val === "string") {
  6243. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6244. }
  6245. return val;
  6246. };
  6247. };
  6248. /**
  6249. * Compute the hashCode of a stream of number
  6250. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6251. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6252. * @return the hash code computed
  6253. */
  6254. Tools.hashCodeFromStream = function (feeder) {
  6255. // Based from here: http://stackoverflow.com/a/7616484/802124
  6256. var hash = 0;
  6257. var index = 0;
  6258. var chr = feeder(index++);
  6259. while (chr != null) {
  6260. hash = ((hash << 5) - hash) + chr;
  6261. hash |= 0; // Convert to 32bit integer
  6262. chr = feeder(index++);
  6263. }
  6264. return hash;
  6265. };
  6266. return Tools;
  6267. }());
  6268. Tools.BaseUrl = "";
  6269. Tools.CorsBehavior = "anonymous";
  6270. Tools.UseFallbackTexture = true;
  6271. // Used in case of a texture loading problem
  6272. 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";
  6273. // Logs
  6274. Tools._NoneLogLevel = 0;
  6275. Tools._MessageLogLevel = 1;
  6276. Tools._WarningLogLevel = 2;
  6277. Tools._ErrorLogLevel = 4;
  6278. Tools._LogCache = "";
  6279. Tools.errorsCount = 0;
  6280. Tools.Log = Tools._LogEnabled;
  6281. Tools.Warn = Tools._WarnEnabled;
  6282. Tools.Error = Tools._ErrorEnabled;
  6283. // Performances
  6284. Tools._PerformanceNoneLogLevel = 0;
  6285. Tools._PerformanceUserMarkLogLevel = 1;
  6286. Tools._PerformanceConsoleLogLevel = 2;
  6287. Tools._performance = window.performance;
  6288. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6289. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6290. BABYLON.Tools = Tools;
  6291. /**
  6292. * This class is used to track a performance counter which is number based.
  6293. * The user has access to many properties which give statistics of different nature
  6294. *
  6295. * The implementer can track two kinds of Performance Counter: time and count
  6296. * 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.
  6297. * 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.
  6298. */
  6299. var PerfCounter = (function () {
  6300. function PerfCounter() {
  6301. this._startMonitoringTime = 0;
  6302. this._min = 0;
  6303. this._max = 0;
  6304. this._average = 0;
  6305. this._lastSecAverage = 0;
  6306. this._current = 0;
  6307. this._totalValueCount = 0;
  6308. this._totalAccumulated = 0;
  6309. this._lastSecAccumulated = 0;
  6310. this._lastSecTime = 0;
  6311. this._lastSecValueCount = 0;
  6312. }
  6313. Object.defineProperty(PerfCounter.prototype, "min", {
  6314. /**
  6315. * Returns the smallest value ever
  6316. */
  6317. get: function () {
  6318. return this._min;
  6319. },
  6320. enumerable: true,
  6321. configurable: true
  6322. });
  6323. Object.defineProperty(PerfCounter.prototype, "max", {
  6324. /**
  6325. * Returns the biggest value ever
  6326. */
  6327. get: function () {
  6328. return this._max;
  6329. },
  6330. enumerable: true,
  6331. configurable: true
  6332. });
  6333. Object.defineProperty(PerfCounter.prototype, "average", {
  6334. /**
  6335. * Returns the average value since the performance counter is running
  6336. */
  6337. get: function () {
  6338. return this._average;
  6339. },
  6340. enumerable: true,
  6341. configurable: true
  6342. });
  6343. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6344. /**
  6345. * Returns the average value of the last second the counter was monitored
  6346. */
  6347. get: function () {
  6348. return this._lastSecAverage;
  6349. },
  6350. enumerable: true,
  6351. configurable: true
  6352. });
  6353. Object.defineProperty(PerfCounter.prototype, "current", {
  6354. /**
  6355. * Returns the current value
  6356. */
  6357. get: function () {
  6358. return this._current;
  6359. },
  6360. enumerable: true,
  6361. configurable: true
  6362. });
  6363. Object.defineProperty(PerfCounter.prototype, "total", {
  6364. get: function () {
  6365. return this._totalAccumulated;
  6366. },
  6367. enumerable: true,
  6368. configurable: true
  6369. });
  6370. /**
  6371. * Call this method to start monitoring a new frame.
  6372. * 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.
  6373. */
  6374. PerfCounter.prototype.fetchNewFrame = function () {
  6375. this._totalValueCount++;
  6376. this._current = 0;
  6377. this._lastSecValueCount++;
  6378. };
  6379. /**
  6380. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6381. * @param newCount the count value to add to the monitored count
  6382. * @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.
  6383. */
  6384. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6385. if (!PerfCounter.Enabled) {
  6386. return;
  6387. }
  6388. this._current += newCount;
  6389. if (fetchResult) {
  6390. this._fetchResult();
  6391. }
  6392. };
  6393. /**
  6394. * Start monitoring this performance counter
  6395. */
  6396. PerfCounter.prototype.beginMonitoring = function () {
  6397. if (!PerfCounter.Enabled) {
  6398. return;
  6399. }
  6400. this._startMonitoringTime = Tools.Now;
  6401. };
  6402. /**
  6403. * Compute the time lapsed since the previous beginMonitoring() call.
  6404. * @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
  6405. */
  6406. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6407. if (newFrame === void 0) { newFrame = true; }
  6408. if (!PerfCounter.Enabled) {
  6409. return;
  6410. }
  6411. if (newFrame) {
  6412. this.fetchNewFrame();
  6413. }
  6414. var currentTime = Tools.Now;
  6415. this._current = currentTime - this._startMonitoringTime;
  6416. if (newFrame) {
  6417. this._fetchResult();
  6418. }
  6419. };
  6420. PerfCounter.prototype._fetchResult = function () {
  6421. this._totalAccumulated += this._current;
  6422. this._lastSecAccumulated += this._current;
  6423. // Min/Max update
  6424. this._min = Math.min(this._min, this._current);
  6425. this._max = Math.max(this._max, this._current);
  6426. this._average = this._totalAccumulated / this._totalValueCount;
  6427. // Reset last sec?
  6428. var now = Tools.Now;
  6429. if ((now - this._lastSecTime) > 1000) {
  6430. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6431. this._lastSecTime = now;
  6432. this._lastSecAccumulated = 0;
  6433. this._lastSecValueCount = 0;
  6434. }
  6435. };
  6436. return PerfCounter;
  6437. }());
  6438. PerfCounter.Enabled = true;
  6439. BABYLON.PerfCounter = PerfCounter;
  6440. /**
  6441. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6442. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6443. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6444. * @param name The name of the class, case should be preserved
  6445. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6446. */
  6447. function className(name, module) {
  6448. return function (target) {
  6449. target["__bjsclassName__"] = name;
  6450. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6451. };
  6452. }
  6453. BABYLON.className = className;
  6454. /**
  6455. * An implementation of a loop for asynchronous functions.
  6456. */
  6457. var AsyncLoop = (function () {
  6458. /**
  6459. * Constroctor.
  6460. * @param iterations the number of iterations.
  6461. * @param _fn the function to run each iteration
  6462. * @param _successCallback the callback that will be called upon succesful execution
  6463. * @param offset starting offset.
  6464. */
  6465. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6466. if (offset === void 0) { offset = 0; }
  6467. this.iterations = iterations;
  6468. this._fn = _fn;
  6469. this._successCallback = _successCallback;
  6470. this.index = offset - 1;
  6471. this._done = false;
  6472. }
  6473. /**
  6474. * Execute the next iteration. Must be called after the last iteration was finished.
  6475. */
  6476. AsyncLoop.prototype.executeNext = function () {
  6477. if (!this._done) {
  6478. if (this.index + 1 < this.iterations) {
  6479. ++this.index;
  6480. this._fn(this);
  6481. }
  6482. else {
  6483. this.breakLoop();
  6484. }
  6485. }
  6486. };
  6487. /**
  6488. * Break the loop and run the success callback.
  6489. */
  6490. AsyncLoop.prototype.breakLoop = function () {
  6491. this._done = true;
  6492. this._successCallback();
  6493. };
  6494. /**
  6495. * Helper function
  6496. */
  6497. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6498. if (offset === void 0) { offset = 0; }
  6499. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6500. loop.executeNext();
  6501. return loop;
  6502. };
  6503. /**
  6504. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6505. * @param iterations total number of iterations
  6506. * @param syncedIterations number of synchronous iterations in each async iteration.
  6507. * @param fn the function to call each iteration.
  6508. * @param callback a success call back that will be called when iterating stops.
  6509. * @param breakFunction a break condition (optional)
  6510. * @param timeout timeout settings for the setTimeout function. default - 0.
  6511. * @constructor
  6512. */
  6513. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6514. if (timeout === void 0) { timeout = 0; }
  6515. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6516. if (breakFunction && breakFunction())
  6517. loop.breakLoop();
  6518. else {
  6519. setTimeout(function () {
  6520. for (var i = 0; i < syncedIterations; ++i) {
  6521. var iteration = (loop.index * syncedIterations) + i;
  6522. if (iteration >= iterations)
  6523. break;
  6524. fn(iteration);
  6525. if (breakFunction && breakFunction()) {
  6526. loop.breakLoop();
  6527. break;
  6528. }
  6529. }
  6530. loop.executeNext();
  6531. }, timeout);
  6532. }
  6533. }, callback);
  6534. };
  6535. return AsyncLoop;
  6536. }());
  6537. BABYLON.AsyncLoop = AsyncLoop;
  6538. })(BABYLON || (BABYLON = {}));
  6539. //# sourceMappingURL=babylon.tools.js.map
  6540. var BABYLON;
  6541. (function (BABYLON) {
  6542. var Internals;
  6543. (function (Internals) {
  6544. var _AlphaState = (function () {
  6545. /**
  6546. * Initializes the state.
  6547. */
  6548. function _AlphaState() {
  6549. this._isAlphaBlendDirty = false;
  6550. this._isBlendFunctionParametersDirty = false;
  6551. this._isBlendEquationParametersDirty = false;
  6552. this._isBlendConstantsDirty = false;
  6553. this._alphaBlend = false;
  6554. this._blendFunctionParameters = new Array(4);
  6555. this._blendEquationParameters = new Array(2);
  6556. this._blendConstants = new Array(4);
  6557. this.reset();
  6558. }
  6559. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6560. get: function () {
  6561. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6562. },
  6563. enumerable: true,
  6564. configurable: true
  6565. });
  6566. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6567. get: function () {
  6568. return this._alphaBlend;
  6569. },
  6570. set: function (value) {
  6571. if (this._alphaBlend === value) {
  6572. return;
  6573. }
  6574. this._alphaBlend = value;
  6575. this._isAlphaBlendDirty = true;
  6576. },
  6577. enumerable: true,
  6578. configurable: true
  6579. });
  6580. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  6581. if (this._blendConstants[0] === r &&
  6582. this._blendConstants[1] === g &&
  6583. this._blendConstants[2] === b &&
  6584. this._blendConstants[3] === a) {
  6585. return;
  6586. }
  6587. this._blendConstants[0] = r;
  6588. this._blendConstants[1] = g;
  6589. this._blendConstants[2] = b;
  6590. this._blendConstants[3] = a;
  6591. this._isBlendConstantsDirty = true;
  6592. };
  6593. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6594. if (this._blendFunctionParameters[0] === value0 &&
  6595. this._blendFunctionParameters[1] === value1 &&
  6596. this._blendFunctionParameters[2] === value2 &&
  6597. this._blendFunctionParameters[3] === value3) {
  6598. return;
  6599. }
  6600. this._blendFunctionParameters[0] = value0;
  6601. this._blendFunctionParameters[1] = value1;
  6602. this._blendFunctionParameters[2] = value2;
  6603. this._blendFunctionParameters[3] = value3;
  6604. this._isBlendFunctionParametersDirty = true;
  6605. };
  6606. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  6607. if (this._blendEquationParameters[0] === rgb &&
  6608. this._blendEquationParameters[1] === alpha) {
  6609. return;
  6610. }
  6611. this._blendEquationParameters[0] = rgb;
  6612. this._blendEquationParameters[1] = alpha;
  6613. this._isBlendEquationParametersDirty = true;
  6614. };
  6615. _AlphaState.prototype.reset = function () {
  6616. this._alphaBlend = false;
  6617. this._blendFunctionParameters[0] = null;
  6618. this._blendFunctionParameters[1] = null;
  6619. this._blendFunctionParameters[2] = null;
  6620. this._blendFunctionParameters[3] = null;
  6621. this._blendEquationParameters[0] = null;
  6622. this._blendEquationParameters[1] = null;
  6623. this._blendConstants[0] = null;
  6624. this._blendConstants[1] = null;
  6625. this._blendConstants[2] = null;
  6626. this._blendConstants[3] = null;
  6627. this._isAlphaBlendDirty = true;
  6628. this._isBlendFunctionParametersDirty = false;
  6629. this._isBlendEquationParametersDirty = false;
  6630. this._isBlendConstantsDirty = false;
  6631. };
  6632. _AlphaState.prototype.apply = function (gl) {
  6633. if (!this.isDirty) {
  6634. return;
  6635. }
  6636. // Alpha blend
  6637. if (this._isAlphaBlendDirty) {
  6638. if (this._alphaBlend) {
  6639. gl.enable(gl.BLEND);
  6640. }
  6641. else {
  6642. gl.disable(gl.BLEND);
  6643. }
  6644. this._isAlphaBlendDirty = false;
  6645. }
  6646. // Alpha function
  6647. if (this._isBlendFunctionParametersDirty) {
  6648. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6649. this._isBlendFunctionParametersDirty = false;
  6650. }
  6651. // Alpha equation
  6652. if (this._isBlendEquationParametersDirty) {
  6653. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  6654. this._isBlendEquationParametersDirty = false;
  6655. }
  6656. // Constants
  6657. if (this._isBlendConstantsDirty) {
  6658. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  6659. this._isBlendConstantsDirty = false;
  6660. }
  6661. };
  6662. return _AlphaState;
  6663. }());
  6664. Internals._AlphaState = _AlphaState;
  6665. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6666. })(BABYLON || (BABYLON = {}));
  6667. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6668. var BABYLON;
  6669. (function (BABYLON) {
  6670. var Internals;
  6671. (function (Internals) {
  6672. var _DepthCullingState = (function () {
  6673. /**
  6674. * Initializes the state.
  6675. */
  6676. function _DepthCullingState() {
  6677. this._isDepthTestDirty = false;
  6678. this._isDepthMaskDirty = false;
  6679. this._isDepthFuncDirty = false;
  6680. this._isCullFaceDirty = false;
  6681. this._isCullDirty = false;
  6682. this._isZOffsetDirty = false;
  6683. this.reset();
  6684. }
  6685. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6686. get: function () {
  6687. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6688. },
  6689. enumerable: true,
  6690. configurable: true
  6691. });
  6692. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6693. get: function () {
  6694. return this._zOffset;
  6695. },
  6696. set: function (value) {
  6697. if (this._zOffset === value) {
  6698. return;
  6699. }
  6700. this._zOffset = value;
  6701. this._isZOffsetDirty = true;
  6702. },
  6703. enumerable: true,
  6704. configurable: true
  6705. });
  6706. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6707. get: function () {
  6708. return this._cullFace;
  6709. },
  6710. set: function (value) {
  6711. if (this._cullFace === value) {
  6712. return;
  6713. }
  6714. this._cullFace = value;
  6715. this._isCullFaceDirty = true;
  6716. },
  6717. enumerable: true,
  6718. configurable: true
  6719. });
  6720. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6721. get: function () {
  6722. return this._cull;
  6723. },
  6724. set: function (value) {
  6725. if (this._cull === value) {
  6726. return;
  6727. }
  6728. this._cull = value;
  6729. this._isCullDirty = true;
  6730. },
  6731. enumerable: true,
  6732. configurable: true
  6733. });
  6734. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6735. get: function () {
  6736. return this._depthFunc;
  6737. },
  6738. set: function (value) {
  6739. if (this._depthFunc === value) {
  6740. return;
  6741. }
  6742. this._depthFunc = value;
  6743. this._isDepthFuncDirty = true;
  6744. },
  6745. enumerable: true,
  6746. configurable: true
  6747. });
  6748. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6749. get: function () {
  6750. return this._depthMask;
  6751. },
  6752. set: function (value) {
  6753. if (this._depthMask === value) {
  6754. return;
  6755. }
  6756. this._depthMask = value;
  6757. this._isDepthMaskDirty = true;
  6758. },
  6759. enumerable: true,
  6760. configurable: true
  6761. });
  6762. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6763. get: function () {
  6764. return this._depthTest;
  6765. },
  6766. set: function (value) {
  6767. if (this._depthTest === value) {
  6768. return;
  6769. }
  6770. this._depthTest = value;
  6771. this._isDepthTestDirty = true;
  6772. },
  6773. enumerable: true,
  6774. configurable: true
  6775. });
  6776. _DepthCullingState.prototype.reset = function () {
  6777. this._depthMask = true;
  6778. this._depthTest = true;
  6779. this._depthFunc = null;
  6780. this._cullFace = null;
  6781. this._cull = null;
  6782. this._zOffset = 0;
  6783. this._isDepthTestDirty = true;
  6784. this._isDepthMaskDirty = true;
  6785. this._isDepthFuncDirty = false;
  6786. this._isCullFaceDirty = false;
  6787. this._isCullDirty = false;
  6788. this._isZOffsetDirty = false;
  6789. };
  6790. _DepthCullingState.prototype.apply = function (gl) {
  6791. if (!this.isDirty) {
  6792. return;
  6793. }
  6794. // Cull
  6795. if (this._isCullDirty) {
  6796. if (this.cull) {
  6797. gl.enable(gl.CULL_FACE);
  6798. }
  6799. else {
  6800. gl.disable(gl.CULL_FACE);
  6801. }
  6802. this._isCullDirty = false;
  6803. }
  6804. // Cull face
  6805. if (this._isCullFaceDirty) {
  6806. gl.cullFace(this.cullFace);
  6807. this._isCullFaceDirty = false;
  6808. }
  6809. // Depth mask
  6810. if (this._isDepthMaskDirty) {
  6811. gl.depthMask(this.depthMask);
  6812. this._isDepthMaskDirty = false;
  6813. }
  6814. // Depth test
  6815. if (this._isDepthTestDirty) {
  6816. if (this.depthTest) {
  6817. gl.enable(gl.DEPTH_TEST);
  6818. }
  6819. else {
  6820. gl.disable(gl.DEPTH_TEST);
  6821. }
  6822. this._isDepthTestDirty = false;
  6823. }
  6824. // Depth func
  6825. if (this._isDepthFuncDirty) {
  6826. gl.depthFunc(this.depthFunc);
  6827. this._isDepthFuncDirty = false;
  6828. }
  6829. // zOffset
  6830. if (this._isZOffsetDirty) {
  6831. if (this.zOffset) {
  6832. gl.enable(gl.POLYGON_OFFSET_FILL);
  6833. gl.polygonOffset(this.zOffset, 0);
  6834. }
  6835. else {
  6836. gl.disable(gl.POLYGON_OFFSET_FILL);
  6837. }
  6838. this._isZOffsetDirty = false;
  6839. }
  6840. };
  6841. return _DepthCullingState;
  6842. }());
  6843. Internals._DepthCullingState = _DepthCullingState;
  6844. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6845. })(BABYLON || (BABYLON = {}));
  6846. //# sourceMappingURL=babylon.depthCullingState.js.map
  6847. var BABYLON;
  6848. (function (BABYLON) {
  6849. var Internals;
  6850. (function (Internals) {
  6851. var _StencilState = (function () {
  6852. function _StencilState() {
  6853. this._isStencilTestDirty = false;
  6854. this._isStencilMaskDirty = false;
  6855. this._isStencilFuncDirty = false;
  6856. this._isStencilOpDirty = false;
  6857. this.reset();
  6858. }
  6859. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6860. get: function () {
  6861. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6862. },
  6863. enumerable: true,
  6864. configurable: true
  6865. });
  6866. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6867. get: function () {
  6868. return this._stencilFunc;
  6869. },
  6870. set: function (value) {
  6871. if (this._stencilFunc === value) {
  6872. return;
  6873. }
  6874. this._stencilFunc = value;
  6875. this._isStencilFuncDirty = true;
  6876. },
  6877. enumerable: true,
  6878. configurable: true
  6879. });
  6880. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6881. get: function () {
  6882. return this._stencilFuncRef;
  6883. },
  6884. set: function (value) {
  6885. if (this._stencilFuncRef === value) {
  6886. return;
  6887. }
  6888. this._stencilFuncRef = value;
  6889. this._isStencilFuncDirty = true;
  6890. },
  6891. enumerable: true,
  6892. configurable: true
  6893. });
  6894. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6895. get: function () {
  6896. return this._stencilFuncMask;
  6897. },
  6898. set: function (value) {
  6899. if (this._stencilFuncMask === value) {
  6900. return;
  6901. }
  6902. this._stencilFuncMask = value;
  6903. this._isStencilFuncDirty = true;
  6904. },
  6905. enumerable: true,
  6906. configurable: true
  6907. });
  6908. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6909. get: function () {
  6910. return this._stencilOpStencilFail;
  6911. },
  6912. set: function (value) {
  6913. if (this._stencilOpStencilFail === value) {
  6914. return;
  6915. }
  6916. this._stencilOpStencilFail = value;
  6917. this._isStencilOpDirty = true;
  6918. },
  6919. enumerable: true,
  6920. configurable: true
  6921. });
  6922. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6923. get: function () {
  6924. return this._stencilOpDepthFail;
  6925. },
  6926. set: function (value) {
  6927. if (this._stencilOpDepthFail === value) {
  6928. return;
  6929. }
  6930. this._stencilOpDepthFail = value;
  6931. this._isStencilOpDirty = true;
  6932. },
  6933. enumerable: true,
  6934. configurable: true
  6935. });
  6936. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6937. get: function () {
  6938. return this._stencilOpStencilDepthPass;
  6939. },
  6940. set: function (value) {
  6941. if (this._stencilOpStencilDepthPass === value) {
  6942. return;
  6943. }
  6944. this._stencilOpStencilDepthPass = value;
  6945. this._isStencilOpDirty = true;
  6946. },
  6947. enumerable: true,
  6948. configurable: true
  6949. });
  6950. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6951. get: function () {
  6952. return this._stencilMask;
  6953. },
  6954. set: function (value) {
  6955. if (this._stencilMask === value) {
  6956. return;
  6957. }
  6958. this._stencilMask = value;
  6959. this._isStencilMaskDirty = true;
  6960. },
  6961. enumerable: true,
  6962. configurable: true
  6963. });
  6964. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6965. get: function () {
  6966. return this._stencilTest;
  6967. },
  6968. set: function (value) {
  6969. if (this._stencilTest === value) {
  6970. return;
  6971. }
  6972. this._stencilTest = value;
  6973. this._isStencilTestDirty = true;
  6974. },
  6975. enumerable: true,
  6976. configurable: true
  6977. });
  6978. _StencilState.prototype.reset = function () {
  6979. this._stencilTest = false;
  6980. this._stencilMask = 0xFF;
  6981. this._stencilFunc = BABYLON.Engine.ALWAYS;
  6982. this._stencilFuncRef = 1;
  6983. this._stencilFuncMask = 0xFF;
  6984. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  6985. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  6986. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  6987. this._isStencilTestDirty = true;
  6988. this._isStencilMaskDirty = true;
  6989. this._isStencilFuncDirty = true;
  6990. this._isStencilOpDirty = true;
  6991. };
  6992. _StencilState.prototype.apply = function (gl) {
  6993. if (!this.isDirty) {
  6994. return;
  6995. }
  6996. // Stencil test
  6997. if (this._isStencilTestDirty) {
  6998. if (this.stencilTest) {
  6999. gl.enable(gl.STENCIL_TEST);
  7000. }
  7001. else {
  7002. gl.disable(gl.STENCIL_TEST);
  7003. }
  7004. this._isStencilTestDirty = false;
  7005. }
  7006. // Stencil mask
  7007. if (this._isStencilMaskDirty) {
  7008. gl.stencilMask(this.stencilMask);
  7009. this._isStencilMaskDirty = false;
  7010. }
  7011. // Stencil func
  7012. if (this._isStencilFuncDirty) {
  7013. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7014. this._isStencilFuncDirty = false;
  7015. }
  7016. // Stencil op
  7017. if (this._isStencilOpDirty) {
  7018. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7019. this._isStencilOpDirty = false;
  7020. }
  7021. };
  7022. return _StencilState;
  7023. }());
  7024. Internals._StencilState = _StencilState;
  7025. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7026. })(BABYLON || (BABYLON = {}));
  7027. //# sourceMappingURL=babylon.stencilState.js.map
  7028. var BABYLON;
  7029. (function (BABYLON) {
  7030. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7031. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7032. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7033. gl.compileShader(shader);
  7034. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7035. throw new Error(gl.getShaderInfoLog(shader));
  7036. }
  7037. return shader;
  7038. };
  7039. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7040. var magFilter = gl.NEAREST;
  7041. var minFilter = gl.NEAREST;
  7042. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7043. magFilter = gl.LINEAR;
  7044. if (generateMipMaps) {
  7045. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7046. }
  7047. else {
  7048. minFilter = gl.LINEAR;
  7049. }
  7050. }
  7051. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7052. magFilter = gl.LINEAR;
  7053. if (generateMipMaps) {
  7054. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7055. }
  7056. else {
  7057. minFilter = gl.LINEAR;
  7058. }
  7059. }
  7060. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7061. magFilter = gl.NEAREST;
  7062. if (generateMipMaps) {
  7063. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7064. }
  7065. else {
  7066. minFilter = gl.NEAREST;
  7067. }
  7068. }
  7069. return {
  7070. min: minFilter,
  7071. mag: magFilter
  7072. };
  7073. };
  7074. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  7075. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7076. var engine = scene.getEngine();
  7077. if (!engine) {
  7078. return;
  7079. }
  7080. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  7081. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  7082. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7083. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7084. texture._baseWidth = width;
  7085. texture._baseHeight = height;
  7086. texture._width = potWidth;
  7087. texture._height = potHeight;
  7088. texture.isReady = true;
  7089. processFunction(potWidth, potHeight);
  7090. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  7091. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7092. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7093. if (!noMipmap && !isCompressed) {
  7094. gl.generateMipmap(gl.TEXTURE_2D);
  7095. }
  7096. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  7097. engine.resetTextureCache();
  7098. scene._removePendingData(texture);
  7099. texture.onLoadedCallbacks.forEach(function (callback) {
  7100. callback();
  7101. });
  7102. texture.onLoadedCallbacks = [];
  7103. };
  7104. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7105. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7106. var img;
  7107. var onload = function () {
  7108. loadedImages[index] = img;
  7109. loadedImages._internalCount++;
  7110. scene._removePendingData(img);
  7111. if (loadedImages._internalCount === 6) {
  7112. onfinish(loadedImages);
  7113. }
  7114. };
  7115. var onerror = function () {
  7116. scene._removePendingData(img);
  7117. if (onErrorCallBack) {
  7118. onErrorCallBack();
  7119. }
  7120. };
  7121. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7122. scene._addPendingData(img);
  7123. };
  7124. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7125. if (onError === void 0) { onError = null; }
  7126. var loadedImages = [];
  7127. loadedImages._internalCount = 0;
  7128. for (var index = 0; index < 6; index++) {
  7129. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7130. }
  7131. };
  7132. var InstancingAttributeInfo = (function () {
  7133. function InstancingAttributeInfo() {
  7134. }
  7135. return InstancingAttributeInfo;
  7136. }());
  7137. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7138. var EngineCapabilities = (function () {
  7139. function EngineCapabilities() {
  7140. }
  7141. return EngineCapabilities;
  7142. }());
  7143. BABYLON.EngineCapabilities = EngineCapabilities;
  7144. /**
  7145. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7146. */
  7147. var Engine = (function () {
  7148. /**
  7149. * @constructor
  7150. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  7151. * @param {boolean} [antialias] - enable antialias
  7152. * @param options - further options to be sent to the getContext function
  7153. */
  7154. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  7155. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7156. var _this = this;
  7157. // Public members
  7158. this.isFullscreen = false;
  7159. this.isPointerLock = false;
  7160. this.cullBackFaces = true;
  7161. this.renderEvenInBackground = true;
  7162. this.preventCacheWipeBetweenFrames = false;
  7163. // To enable/disable IDB support and avoid XHR on .manifest
  7164. this.enableOfflineSupport = BABYLON.Database;
  7165. this.scenes = new Array();
  7166. // Observables
  7167. /**
  7168. * Observable event triggered each time the rendering canvas is resized
  7169. */
  7170. this.onResizeObservable = new BABYLON.Observable();
  7171. /**
  7172. * Observable event triggered each time the canvas lost focus
  7173. */
  7174. this.onCanvasBlurObservable = new BABYLON.Observable();
  7175. this._windowIsBackground = false;
  7176. this._webGLVersion = 1.0;
  7177. this._badOS = false;
  7178. this._drawCalls = new BABYLON.PerfCounter();
  7179. this._renderingQueueLaunched = false;
  7180. this._activeRenderLoops = [];
  7181. // FPS
  7182. this.fpsRange = 60;
  7183. this.previousFramesDuration = [];
  7184. this.fps = 60;
  7185. this.deltaTime = 0;
  7186. // States
  7187. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7188. this._stencilState = new BABYLON.Internals._StencilState();
  7189. this._alphaState = new BABYLON.Internals._AlphaState();
  7190. this._alphaMode = Engine.ALPHA_DISABLE;
  7191. // Cache
  7192. this._loadedTexturesCache = new Array();
  7193. this._maxTextureChannels = 16;
  7194. this._activeTexturesCache = new Array(this._maxTextureChannels);
  7195. this._compiledEffects = {};
  7196. this._vertexAttribArraysEnabled = [];
  7197. this._uintIndicesCurrentlySet = false;
  7198. this._currentBoundBuffer = new Array();
  7199. this._currentBufferPointers = [];
  7200. this._currentInstanceLocations = new Array();
  7201. this._currentInstanceBuffers = new Array();
  7202. this._vaoRecordInProgress = false;
  7203. this._mustWipeVertexAttributes = false;
  7204. // Hardware supported Compressed Textures
  7205. this._texturesSupported = new Array();
  7206. this._onVRFullScreenTriggered = function () {
  7207. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7208. //get the old size before we change
  7209. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7210. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7211. //get the width and height, change the render size
  7212. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7213. var width, height;
  7214. _this.setHardwareScalingLevel(1);
  7215. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7216. }
  7217. else {
  7218. //When the specs are implemented, need to uncomment this.
  7219. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7220. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7221. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7222. _this._vrDisplayEnabled = undefined;
  7223. }
  7224. };
  7225. this._renderingCanvas = canvas;
  7226. Engine.Instances.push(this);
  7227. options = options || {};
  7228. if (antialias != null) {
  7229. options.antialias = antialias;
  7230. }
  7231. if (options.preserveDrawingBuffer === undefined) {
  7232. options.preserveDrawingBuffer = false;
  7233. }
  7234. if (options.audioEngine === undefined) {
  7235. options.audioEngine = true;
  7236. }
  7237. if (options.stencil === undefined) {
  7238. options.stencil = true;
  7239. }
  7240. // GL
  7241. if (!options.disableWebGL2Support) {
  7242. try {
  7243. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7244. if (this._gl) {
  7245. this._webGLVersion = 2.0;
  7246. }
  7247. }
  7248. catch (e) {
  7249. // Do nothing
  7250. }
  7251. }
  7252. if (!this._gl) {
  7253. if (!canvas) {
  7254. throw new Error("The provided canvas is null or undefined.");
  7255. }
  7256. try {
  7257. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7258. }
  7259. catch (e) {
  7260. throw new Error("WebGL not supported");
  7261. }
  7262. }
  7263. if (!this._gl) {
  7264. throw new Error("WebGL not supported");
  7265. }
  7266. this._onBlur = function () {
  7267. _this._windowIsBackground = true;
  7268. };
  7269. this._onFocus = function () {
  7270. _this._windowIsBackground = false;
  7271. };
  7272. this._onCanvasBlur = function () {
  7273. _this.onCanvasBlurObservable.notifyObservers(_this);
  7274. };
  7275. window.addEventListener("blur", this._onBlur);
  7276. window.addEventListener("focus", this._onFocus);
  7277. canvas.addEventListener("pointerout", this._onCanvasBlur);
  7278. // Viewport
  7279. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7280. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7281. this.resize();
  7282. // Caps
  7283. this._isStencilEnable = options.stencil;
  7284. this._caps = new EngineCapabilities();
  7285. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  7286. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  7287. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  7288. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  7289. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  7290. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  7291. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  7292. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  7293. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  7294. // Infos
  7295. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  7296. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  7297. if (rendererInfo != null) {
  7298. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  7299. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  7300. }
  7301. if (!this._glVendor) {
  7302. this._glVendor = "Unknown vendor";
  7303. }
  7304. if (!this._glRenderer) {
  7305. this._glRenderer = "Unknown renderer";
  7306. }
  7307. // Extensions
  7308. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  7309. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  7310. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  7311. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  7312. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  7313. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  7314. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  7315. 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');
  7316. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  7317. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  7318. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  7319. this._caps.highPrecisionShaderSupported = true;
  7320. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  7321. // Checks if some of the format renders first to allow the use of webgl inspector.
  7322. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  7323. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  7324. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  7325. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  7326. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  7327. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  7328. if (this._webGLVersion > 1) {
  7329. Engine.HALF_FLOAT_OES = 0x140B;
  7330. }
  7331. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  7332. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  7333. // Vertex array object
  7334. if (this._webGLVersion > 1) {
  7335. this._caps.vertexArrayObject = true;
  7336. }
  7337. else {
  7338. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  7339. if (vertexArrayObjectExtension != null) {
  7340. this._caps.vertexArrayObject = true;
  7341. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  7342. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  7343. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  7344. }
  7345. else {
  7346. this._caps.vertexArrayObject = false;
  7347. }
  7348. }
  7349. // Instances count
  7350. if (this._webGLVersion > 1) {
  7351. this._caps.instancedArrays = true;
  7352. }
  7353. else {
  7354. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  7355. if (instanceExtension != null) {
  7356. this._caps.instancedArrays = true;
  7357. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  7358. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  7359. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  7360. }
  7361. else {
  7362. this._caps.instancedArrays = false;
  7363. }
  7364. }
  7365. // Intelligently add supported compressed formats in order to check for.
  7366. // Check for ASTC support first as it is most powerful and to be very cross platform.
  7367. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  7368. // Likely no hardware which supports both PVR & DXT, so order matters little.
  7369. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  7370. if (this._caps.astc)
  7371. this.texturesSupported.push('-astc.ktx');
  7372. if (this._caps.s3tc)
  7373. this.texturesSupported.push('-dxt.ktx');
  7374. if (this._caps.pvrtc)
  7375. this.texturesSupported.push('-pvrtc.ktx');
  7376. if (this._caps.etc2)
  7377. this.texturesSupported.push('-etc2.ktx');
  7378. if (this._caps.etc1)
  7379. this.texturesSupported.push('-etc1.ktx');
  7380. if (this._gl.getShaderPrecisionFormat) {
  7381. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  7382. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  7383. }
  7384. // Depth buffer
  7385. this.setDepthBuffer(true);
  7386. this.setDepthFunctionToLessOrEqual();
  7387. this.setDepthWrite(true);
  7388. // Fullscreen
  7389. this._onFullscreenChange = function () {
  7390. if (document.fullscreen !== undefined) {
  7391. _this.isFullscreen = document.fullscreen;
  7392. }
  7393. else if (document.mozFullScreen !== undefined) {
  7394. _this.isFullscreen = document.mozFullScreen;
  7395. }
  7396. else if (document.webkitIsFullScreen !== undefined) {
  7397. _this.isFullscreen = document.webkitIsFullScreen;
  7398. }
  7399. else if (document.msIsFullScreen !== undefined) {
  7400. _this.isFullscreen = document.msIsFullScreen;
  7401. }
  7402. // Pointer lock
  7403. if (_this.isFullscreen && _this._pointerLockRequested) {
  7404. canvas.requestPointerLock = canvas.requestPointerLock ||
  7405. canvas.msRequestPointerLock ||
  7406. canvas.mozRequestPointerLock ||
  7407. canvas.webkitRequestPointerLock;
  7408. if (canvas.requestPointerLock) {
  7409. canvas.requestPointerLock();
  7410. }
  7411. }
  7412. };
  7413. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7414. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7415. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7416. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7417. // Pointer lock
  7418. this._onPointerLockChange = function () {
  7419. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7420. document.webkitPointerLockElement === canvas ||
  7421. document.msPointerLockElement === canvas ||
  7422. document.pointerLockElement === canvas);
  7423. };
  7424. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7425. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7426. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7427. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7428. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7429. Engine.audioEngine = new BABYLON.AudioEngine();
  7430. }
  7431. //Load WebVR Devices
  7432. if (options.autoEnableWebVR) {
  7433. this.initWebVR();
  7434. }
  7435. //Detect if we are running on a faulty buggy OS.
  7436. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  7437. //ua sniffing is the tool of the devil.
  7438. this._badOS = regexp.test(navigator.userAgent);
  7439. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7440. }
  7441. Object.defineProperty(Engine, "LastCreatedEngine", {
  7442. get: function () {
  7443. if (Engine.Instances.length === 0) {
  7444. return null;
  7445. }
  7446. return Engine.Instances[Engine.Instances.length - 1];
  7447. },
  7448. enumerable: true,
  7449. configurable: true
  7450. });
  7451. Object.defineProperty(Engine, "LastCreatedScene", {
  7452. get: function () {
  7453. var lastCreatedEngine = Engine.LastCreatedEngine;
  7454. if (!lastCreatedEngine) {
  7455. return null;
  7456. }
  7457. if (lastCreatedEngine.scenes.length === 0) {
  7458. return null;
  7459. }
  7460. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7461. },
  7462. enumerable: true,
  7463. configurable: true
  7464. });
  7465. /**
  7466. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7467. */
  7468. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7469. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7470. var engine = Engine.Instances[engineIndex];
  7471. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7472. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7473. }
  7474. }
  7475. };
  7476. Object.defineProperty(Engine, "NEVER", {
  7477. get: function () {
  7478. return Engine._NEVER;
  7479. },
  7480. enumerable: true,
  7481. configurable: true
  7482. });
  7483. Object.defineProperty(Engine, "ALWAYS", {
  7484. get: function () {
  7485. return Engine._ALWAYS;
  7486. },
  7487. enumerable: true,
  7488. configurable: true
  7489. });
  7490. Object.defineProperty(Engine, "LESS", {
  7491. get: function () {
  7492. return Engine._LESS;
  7493. },
  7494. enumerable: true,
  7495. configurable: true
  7496. });
  7497. Object.defineProperty(Engine, "EQUAL", {
  7498. get: function () {
  7499. return Engine._EQUAL;
  7500. },
  7501. enumerable: true,
  7502. configurable: true
  7503. });
  7504. Object.defineProperty(Engine, "LEQUAL", {
  7505. get: function () {
  7506. return Engine._LEQUAL;
  7507. },
  7508. enumerable: true,
  7509. configurable: true
  7510. });
  7511. Object.defineProperty(Engine, "GREATER", {
  7512. get: function () {
  7513. return Engine._GREATER;
  7514. },
  7515. enumerable: true,
  7516. configurable: true
  7517. });
  7518. Object.defineProperty(Engine, "GEQUAL", {
  7519. get: function () {
  7520. return Engine._GEQUAL;
  7521. },
  7522. enumerable: true,
  7523. configurable: true
  7524. });
  7525. Object.defineProperty(Engine, "NOTEQUAL", {
  7526. get: function () {
  7527. return Engine._NOTEQUAL;
  7528. },
  7529. enumerable: true,
  7530. configurable: true
  7531. });
  7532. Object.defineProperty(Engine, "KEEP", {
  7533. get: function () {
  7534. return Engine._KEEP;
  7535. },
  7536. enumerable: true,
  7537. configurable: true
  7538. });
  7539. Object.defineProperty(Engine, "REPLACE", {
  7540. get: function () {
  7541. return Engine._REPLACE;
  7542. },
  7543. enumerable: true,
  7544. configurable: true
  7545. });
  7546. Object.defineProperty(Engine, "INCR", {
  7547. get: function () {
  7548. return Engine._INCR;
  7549. },
  7550. enumerable: true,
  7551. configurable: true
  7552. });
  7553. Object.defineProperty(Engine, "DECR", {
  7554. get: function () {
  7555. return Engine._DECR;
  7556. },
  7557. enumerable: true,
  7558. configurable: true
  7559. });
  7560. Object.defineProperty(Engine, "INVERT", {
  7561. get: function () {
  7562. return Engine._INVERT;
  7563. },
  7564. enumerable: true,
  7565. configurable: true
  7566. });
  7567. Object.defineProperty(Engine, "INCR_WRAP", {
  7568. get: function () {
  7569. return Engine._INCR_WRAP;
  7570. },
  7571. enumerable: true,
  7572. configurable: true
  7573. });
  7574. Object.defineProperty(Engine, "DECR_WRAP", {
  7575. get: function () {
  7576. return Engine._DECR_WRAP;
  7577. },
  7578. enumerable: true,
  7579. configurable: true
  7580. });
  7581. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  7582. get: function () {
  7583. return Engine._ALPHA_DISABLE;
  7584. },
  7585. enumerable: true,
  7586. configurable: true
  7587. });
  7588. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  7589. get: function () {
  7590. return Engine._ALPHA_ONEONE;
  7591. },
  7592. enumerable: true,
  7593. configurable: true
  7594. });
  7595. Object.defineProperty(Engine, "ALPHA_ADD", {
  7596. get: function () {
  7597. return Engine._ALPHA_ADD;
  7598. },
  7599. enumerable: true,
  7600. configurable: true
  7601. });
  7602. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  7603. get: function () {
  7604. return Engine._ALPHA_COMBINE;
  7605. },
  7606. enumerable: true,
  7607. configurable: true
  7608. });
  7609. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  7610. get: function () {
  7611. return Engine._ALPHA_SUBTRACT;
  7612. },
  7613. enumerable: true,
  7614. configurable: true
  7615. });
  7616. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  7617. get: function () {
  7618. return Engine._ALPHA_MULTIPLY;
  7619. },
  7620. enumerable: true,
  7621. configurable: true
  7622. });
  7623. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  7624. get: function () {
  7625. return Engine._ALPHA_MAXIMIZED;
  7626. },
  7627. enumerable: true,
  7628. configurable: true
  7629. });
  7630. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  7631. get: function () {
  7632. return Engine._ALPHA_PREMULTIPLIED;
  7633. },
  7634. enumerable: true,
  7635. configurable: true
  7636. });
  7637. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  7638. get: function () {
  7639. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  7640. },
  7641. enumerable: true,
  7642. configurable: true
  7643. });
  7644. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  7645. get: function () {
  7646. return Engine._ALPHA_INTERPOLATE;
  7647. },
  7648. enumerable: true,
  7649. configurable: true
  7650. });
  7651. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  7652. get: function () {
  7653. return Engine._ALPHA_SCREENMODE;
  7654. },
  7655. enumerable: true,
  7656. configurable: true
  7657. });
  7658. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  7659. get: function () {
  7660. return Engine._DELAYLOADSTATE_NONE;
  7661. },
  7662. enumerable: true,
  7663. configurable: true
  7664. });
  7665. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  7666. get: function () {
  7667. return Engine._DELAYLOADSTATE_LOADED;
  7668. },
  7669. enumerable: true,
  7670. configurable: true
  7671. });
  7672. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  7673. get: function () {
  7674. return Engine._DELAYLOADSTATE_LOADING;
  7675. },
  7676. enumerable: true,
  7677. configurable: true
  7678. });
  7679. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  7680. get: function () {
  7681. return Engine._DELAYLOADSTATE_NOTLOADED;
  7682. },
  7683. enumerable: true,
  7684. configurable: true
  7685. });
  7686. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  7687. get: function () {
  7688. return Engine._TEXTUREFORMAT_ALPHA;
  7689. },
  7690. enumerable: true,
  7691. configurable: true
  7692. });
  7693. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  7694. get: function () {
  7695. return Engine._TEXTUREFORMAT_LUMINANCE;
  7696. },
  7697. enumerable: true,
  7698. configurable: true
  7699. });
  7700. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  7701. get: function () {
  7702. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  7703. },
  7704. enumerable: true,
  7705. configurable: true
  7706. });
  7707. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  7708. get: function () {
  7709. return Engine._TEXTUREFORMAT_RGB;
  7710. },
  7711. enumerable: true,
  7712. configurable: true
  7713. });
  7714. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  7715. get: function () {
  7716. return Engine._TEXTUREFORMAT_RGBA;
  7717. },
  7718. enumerable: true,
  7719. configurable: true
  7720. });
  7721. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  7722. get: function () {
  7723. return Engine._TEXTURETYPE_UNSIGNED_INT;
  7724. },
  7725. enumerable: true,
  7726. configurable: true
  7727. });
  7728. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  7729. get: function () {
  7730. return Engine._TEXTURETYPE_FLOAT;
  7731. },
  7732. enumerable: true,
  7733. configurable: true
  7734. });
  7735. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  7736. get: function () {
  7737. return Engine._TEXTURETYPE_HALF_FLOAT;
  7738. },
  7739. enumerable: true,
  7740. configurable: true
  7741. });
  7742. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  7743. get: function () {
  7744. return Engine._SCALEMODE_FLOOR;
  7745. },
  7746. enumerable: true,
  7747. configurable: true
  7748. });
  7749. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  7750. get: function () {
  7751. return Engine._SCALEMODE_NEAREST;
  7752. },
  7753. enumerable: true,
  7754. configurable: true
  7755. });
  7756. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  7757. get: function () {
  7758. return Engine._SCALEMODE_CEILING;
  7759. },
  7760. enumerable: true,
  7761. configurable: true
  7762. });
  7763. Object.defineProperty(Engine, "Version", {
  7764. get: function () {
  7765. return "3.0-beta";
  7766. },
  7767. enumerable: true,
  7768. configurable: true
  7769. });
  7770. Object.defineProperty(Engine.prototype, "texturesSupported", {
  7771. get: function () {
  7772. return this._texturesSupported;
  7773. },
  7774. enumerable: true,
  7775. configurable: true
  7776. });
  7777. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  7778. get: function () {
  7779. return this._textureFormatInUse;
  7780. },
  7781. enumerable: true,
  7782. configurable: true
  7783. });
  7784. Object.defineProperty(Engine.prototype, "emptyTexture", {
  7785. // Empty texture
  7786. get: function () {
  7787. if (!this._emptyTexture) {
  7788. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7789. }
  7790. return this._emptyTexture;
  7791. },
  7792. enumerable: true,
  7793. configurable: true
  7794. });
  7795. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  7796. get: function () {
  7797. if (!this._emptyCubeTexture) {
  7798. var faceData = new Uint8Array(4);
  7799. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  7800. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7801. }
  7802. return this._emptyCubeTexture;
  7803. },
  7804. enumerable: true,
  7805. configurable: true
  7806. });
  7807. Object.defineProperty(Engine.prototype, "webGLVersion", {
  7808. get: function () {
  7809. return this._webGLVersion;
  7810. },
  7811. enumerable: true,
  7812. configurable: true
  7813. });
  7814. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  7815. /**
  7816. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  7817. */
  7818. get: function () {
  7819. return this._isStencilEnable;
  7820. },
  7821. enumerable: true,
  7822. configurable: true
  7823. });
  7824. Engine.prototype._prepareWorkingCanvas = function () {
  7825. if (this._workingCanvas) {
  7826. return;
  7827. }
  7828. this._workingCanvas = document.createElement("canvas");
  7829. this._workingContext = this._workingCanvas.getContext("2d");
  7830. };
  7831. Engine.prototype.resetTextureCache = function () {
  7832. for (var index = 0; index < this._maxTextureChannels; index++) {
  7833. this._activeTexturesCache[index] = null;
  7834. }
  7835. };
  7836. Engine.prototype.getGlInfo = function () {
  7837. return {
  7838. vendor: this._glVendor,
  7839. renderer: this._glRenderer,
  7840. version: this._glVersion
  7841. };
  7842. };
  7843. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  7844. if (useScreen === void 0) { useScreen = false; }
  7845. var viewport = camera.viewport;
  7846. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  7847. };
  7848. Engine.prototype.getRenderWidth = function (useScreen) {
  7849. if (useScreen === void 0) { useScreen = false; }
  7850. if (!useScreen && this._currentRenderTarget) {
  7851. return this._currentRenderTarget._width;
  7852. }
  7853. return this._renderingCanvas.width;
  7854. };
  7855. Engine.prototype.getRenderHeight = function (useScreen) {
  7856. if (useScreen === void 0) { useScreen = false; }
  7857. if (!useScreen && this._currentRenderTarget) {
  7858. return this._currentRenderTarget._height;
  7859. }
  7860. return this._renderingCanvas.height;
  7861. };
  7862. Engine.prototype.getRenderingCanvas = function () {
  7863. return this._renderingCanvas;
  7864. };
  7865. Engine.prototype.getRenderingCanvasClientRect = function () {
  7866. return this._renderingCanvas.getBoundingClientRect();
  7867. };
  7868. Engine.prototype.setHardwareScalingLevel = function (level) {
  7869. this._hardwareScalingLevel = level;
  7870. this.resize();
  7871. };
  7872. Engine.prototype.getHardwareScalingLevel = function () {
  7873. return this._hardwareScalingLevel;
  7874. };
  7875. Engine.prototype.getLoadedTexturesCache = function () {
  7876. return this._loadedTexturesCache;
  7877. };
  7878. Engine.prototype.getCaps = function () {
  7879. return this._caps;
  7880. };
  7881. Object.defineProperty(Engine.prototype, "drawCalls", {
  7882. get: function () {
  7883. return this._drawCalls.current;
  7884. },
  7885. enumerable: true,
  7886. configurable: true
  7887. });
  7888. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  7889. get: function () {
  7890. return this._drawCalls;
  7891. },
  7892. enumerable: true,
  7893. configurable: true
  7894. });
  7895. Engine.prototype.getDepthFunction = function () {
  7896. return this._depthCullingState.depthFunc;
  7897. };
  7898. Engine.prototype.setDepthFunction = function (depthFunc) {
  7899. this._depthCullingState.depthFunc = depthFunc;
  7900. };
  7901. Engine.prototype.setDepthFunctionToGreater = function () {
  7902. this._depthCullingState.depthFunc = this._gl.GREATER;
  7903. };
  7904. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  7905. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  7906. };
  7907. Engine.prototype.setDepthFunctionToLess = function () {
  7908. this._depthCullingState.depthFunc = this._gl.LESS;
  7909. };
  7910. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  7911. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  7912. };
  7913. Engine.prototype.getStencilBuffer = function () {
  7914. return this._stencilState.stencilTest;
  7915. };
  7916. Engine.prototype.setStencilBuffer = function (enable) {
  7917. this._stencilState.stencilTest = enable;
  7918. };
  7919. Engine.prototype.getStencilMask = function () {
  7920. return this._stencilState.stencilMask;
  7921. };
  7922. Engine.prototype.setStencilMask = function (mask) {
  7923. this._stencilState.stencilMask = mask;
  7924. };
  7925. Engine.prototype.getStencilFunction = function () {
  7926. return this._stencilState.stencilFunc;
  7927. };
  7928. Engine.prototype.getStencilFunctionReference = function () {
  7929. return this._stencilState.stencilFuncRef;
  7930. };
  7931. Engine.prototype.getStencilFunctionMask = function () {
  7932. return this._stencilState.stencilFuncMask;
  7933. };
  7934. Engine.prototype.setStencilFunction = function (stencilFunc) {
  7935. this._stencilState.stencilFunc = stencilFunc;
  7936. };
  7937. Engine.prototype.setStencilFunctionReference = function (reference) {
  7938. this._stencilState.stencilFuncRef = reference;
  7939. };
  7940. Engine.prototype.setStencilFunctionMask = function (mask) {
  7941. this._stencilState.stencilFuncMask = mask;
  7942. };
  7943. Engine.prototype.getStencilOperationFail = function () {
  7944. return this._stencilState.stencilOpStencilFail;
  7945. };
  7946. Engine.prototype.getStencilOperationDepthFail = function () {
  7947. return this._stencilState.stencilOpDepthFail;
  7948. };
  7949. Engine.prototype.getStencilOperationPass = function () {
  7950. return this._stencilState.stencilOpStencilDepthPass;
  7951. };
  7952. Engine.prototype.setStencilOperationFail = function (operation) {
  7953. this._stencilState.stencilOpStencilFail = operation;
  7954. };
  7955. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  7956. this._stencilState.stencilOpDepthFail = operation;
  7957. };
  7958. Engine.prototype.setStencilOperationPass = function (operation) {
  7959. this._stencilState.stencilOpStencilDepthPass = operation;
  7960. };
  7961. Engine.prototype.setDitheringState = function (value) {
  7962. if (value) {
  7963. this._gl.enable(this._gl.DITHER);
  7964. }
  7965. else {
  7966. this._gl.disable(this._gl.DITHER);
  7967. }
  7968. };
  7969. /**
  7970. * stop executing a render loop function and remove it from the execution array
  7971. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  7972. */
  7973. Engine.prototype.stopRenderLoop = function (renderFunction) {
  7974. if (!renderFunction) {
  7975. this._activeRenderLoops = [];
  7976. return;
  7977. }
  7978. var index = this._activeRenderLoops.indexOf(renderFunction);
  7979. if (index >= 0) {
  7980. this._activeRenderLoops.splice(index, 1);
  7981. }
  7982. };
  7983. Engine.prototype._renderLoop = function () {
  7984. var shouldRender = true;
  7985. if (!this.renderEvenInBackground && this._windowIsBackground) {
  7986. shouldRender = false;
  7987. }
  7988. if (shouldRender) {
  7989. // Start new frame
  7990. this.beginFrame();
  7991. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  7992. var renderFunction = this._activeRenderLoops[index];
  7993. renderFunction();
  7994. }
  7995. // Present
  7996. this.endFrame();
  7997. }
  7998. if (this._activeRenderLoops.length > 0) {
  7999. // Register new frame
  8000. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8001. }
  8002. else {
  8003. this._renderingQueueLaunched = false;
  8004. }
  8005. };
  8006. /**
  8007. * Register and execute a render loop. The engine can have more than one render function.
  8008. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8009. * @example
  8010. * engine.runRenderLoop(function () {
  8011. * scene.render()
  8012. * })
  8013. */
  8014. Engine.prototype.runRenderLoop = function (renderFunction) {
  8015. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8016. return;
  8017. }
  8018. this._activeRenderLoops.push(renderFunction);
  8019. if (!this._renderingQueueLaunched) {
  8020. this._renderingQueueLaunched = true;
  8021. this._bindedRenderFunction = this._renderLoop.bind(this);
  8022. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8023. }
  8024. };
  8025. /**
  8026. * Toggle full screen mode.
  8027. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8028. * @param {any} options - an options object to be sent to the requestFullscreen function
  8029. */
  8030. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8031. if (this.isFullscreen) {
  8032. BABYLON.Tools.ExitFullscreen();
  8033. }
  8034. else {
  8035. this._pointerLockRequested = requestPointerLock;
  8036. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8037. }
  8038. };
  8039. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8040. if (stencil === void 0) { stencil = false; }
  8041. this.applyStates();
  8042. var mode = 0;
  8043. if (backBuffer && color) {
  8044. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8045. mode |= this._gl.COLOR_BUFFER_BIT;
  8046. }
  8047. if (depth) {
  8048. this._gl.clearDepth(1.0);
  8049. mode |= this._gl.DEPTH_BUFFER_BIT;
  8050. }
  8051. if (stencil) {
  8052. this._gl.clearStencil(0);
  8053. mode |= this._gl.STENCIL_BUFFER_BIT;
  8054. }
  8055. this._gl.clear(mode);
  8056. };
  8057. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8058. var gl = this._gl;
  8059. // Save state
  8060. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8061. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8062. // Change state
  8063. gl.enable(gl.SCISSOR_TEST);
  8064. gl.scissor(x, y, width, height);
  8065. // Clear
  8066. this.clear(clearColor, true, true, true);
  8067. // Restore state
  8068. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8069. if (curScissor === true) {
  8070. gl.enable(gl.SCISSOR_TEST);
  8071. }
  8072. else {
  8073. gl.disable(gl.SCISSOR_TEST);
  8074. }
  8075. };
  8076. /**
  8077. * Set the WebGL's viewport
  8078. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8079. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8080. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8081. */
  8082. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8083. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  8084. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  8085. var x = viewport.x || 0;
  8086. var y = viewport.y || 0;
  8087. this._cachedViewport = viewport;
  8088. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8089. };
  8090. /**
  8091. * Directly set the WebGL Viewport
  8092. * The x, y, width & height are directly passed to the WebGL call
  8093. * @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.
  8094. */
  8095. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8096. var currentViewport = this._cachedViewport;
  8097. this._cachedViewport = null;
  8098. this._gl.viewport(x, y, width, height);
  8099. return currentViewport;
  8100. };
  8101. Engine.prototype.beginFrame = function () {
  8102. this._measureFps();
  8103. };
  8104. Engine.prototype.endFrame = function () {
  8105. //force a flush in case we are using a bad OS.
  8106. if (this._badOS) {
  8107. this.flushFramebuffer();
  8108. }
  8109. //submit frame to the vr device, if enabled
  8110. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8111. this._vrDisplayEnabled.submitFrame();
  8112. }
  8113. };
  8114. /**
  8115. * resize the view according to the canvas' size.
  8116. * @example
  8117. * window.addEventListener("resize", function () {
  8118. * engine.resize();
  8119. * });
  8120. */
  8121. Engine.prototype.resize = function () {
  8122. // We're not resizing the size of the canvas while in VR mode & presenting
  8123. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8124. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8125. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8126. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8127. }
  8128. };
  8129. /**
  8130. * force a specific size of the canvas
  8131. * @param {number} width - the new canvas' width
  8132. * @param {number} height - the new canvas' height
  8133. */
  8134. Engine.prototype.setSize = function (width, height) {
  8135. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8136. return;
  8137. }
  8138. this._renderingCanvas.width = width;
  8139. this._renderingCanvas.height = height;
  8140. for (var index = 0; index < this.scenes.length; index++) {
  8141. var scene = this.scenes[index];
  8142. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8143. var cam = scene.cameras[camIndex];
  8144. cam._currentRenderId = 0;
  8145. }
  8146. }
  8147. if (this.onResizeObservable.hasObservers) {
  8148. this.onResizeObservable.notifyObservers(this);
  8149. }
  8150. };
  8151. //WebVR functions
  8152. Engine.prototype.isVRDevicePresent = function (callback) {
  8153. this.getVRDevice(null, function (device) {
  8154. callback(device !== null);
  8155. });
  8156. };
  8157. Engine.prototype.getVRDevice = function (name, callback) {
  8158. if (!this.vrDisplaysPromise) {
  8159. callback(null);
  8160. return;
  8161. }
  8162. this.vrDisplaysPromise.then(function (devices) {
  8163. if (devices.length > 0) {
  8164. if (name) {
  8165. var found = devices.some(function (device) {
  8166. if (device.displayName === name) {
  8167. callback(device);
  8168. return true;
  8169. }
  8170. else {
  8171. return false;
  8172. }
  8173. });
  8174. if (!found) {
  8175. BABYLON.Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  8176. callback(devices[0]);
  8177. }
  8178. }
  8179. else {
  8180. //choose the first one
  8181. callback(devices[0]);
  8182. }
  8183. }
  8184. else {
  8185. BABYLON.Tools.Error("No WebVR devices found!");
  8186. callback(null);
  8187. }
  8188. });
  8189. };
  8190. Engine.prototype.initWebVR = function () {
  8191. if (!this.vrDisplaysPromise) {
  8192. this._getVRDisplays();
  8193. }
  8194. };
  8195. Engine.prototype.enableVR = function (vrDevice) {
  8196. this._vrDisplayEnabled = vrDevice;
  8197. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8198. };
  8199. Engine.prototype.disableVR = function () {
  8200. if (this._vrDisplayEnabled) {
  8201. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8202. }
  8203. };
  8204. Engine.prototype._getVRDisplays = function () {
  8205. var _this = this;
  8206. var getWebVRDevices = function (devices) {
  8207. var size = devices.length;
  8208. var i = 0;
  8209. _this._vrDisplays = devices.filter(function (device) {
  8210. return devices[i] instanceof VRDisplay;
  8211. });
  8212. return _this._vrDisplays;
  8213. };
  8214. //using a key due to typescript
  8215. if (navigator.getVRDisplays) {
  8216. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8217. }
  8218. };
  8219. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  8220. this._currentRenderTarget = texture;
  8221. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8222. var gl = this._gl;
  8223. if (texture.isCube) {
  8224. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  8225. }
  8226. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  8227. this.wipeCaches();
  8228. };
  8229. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8230. if (this._currentFramebuffer !== framebuffer) {
  8231. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8232. this._currentFramebuffer = framebuffer;
  8233. }
  8234. };
  8235. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8236. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8237. this._currentRenderTarget = null;
  8238. // If MSAA, we need to bitblt back to main texture
  8239. var gl = this._gl;
  8240. if (texture._MSAAFramebuffer) {
  8241. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8242. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8243. gl.blitFramebuffer(0, 0, texture._width, texture._height, 0, 0, texture._width, texture._height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8244. }
  8245. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  8246. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8247. gl.generateMipmap(gl.TEXTURE_2D);
  8248. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8249. }
  8250. if (onBeforeUnbind) {
  8251. if (texture._MSAAFramebuffer) {
  8252. // Bind the correct framebuffer
  8253. this.bindUnboundFramebuffer(texture._framebuffer);
  8254. }
  8255. onBeforeUnbind();
  8256. }
  8257. this.bindUnboundFramebuffer(null);
  8258. };
  8259. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8260. if (texture.generateMipMaps) {
  8261. var gl = this._gl;
  8262. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8263. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8264. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8265. }
  8266. };
  8267. Engine.prototype.flushFramebuffer = function () {
  8268. this._gl.flush();
  8269. };
  8270. Engine.prototype.restoreDefaultFramebuffer = function () {
  8271. this._currentRenderTarget = null;
  8272. this.bindUnboundFramebuffer(null);
  8273. this.setViewport(this._cachedViewport);
  8274. this.wipeCaches();
  8275. };
  8276. // UBOs
  8277. Engine.prototype.createUniformBuffer = function (elements) {
  8278. var ubo = this._gl.createBuffer();
  8279. this.bindUniformBuffer(ubo);
  8280. if (elements instanceof Float32Array) {
  8281. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8282. }
  8283. else {
  8284. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8285. }
  8286. this.bindUniformBuffer(null);
  8287. ubo.references = 1;
  8288. return ubo;
  8289. };
  8290. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8291. var ubo = this._gl.createBuffer();
  8292. this.bindUniformBuffer(ubo);
  8293. if (elements instanceof Float32Array) {
  8294. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8295. }
  8296. else {
  8297. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8298. }
  8299. this.bindUniformBuffer(null);
  8300. ubo.references = 1;
  8301. return ubo;
  8302. };
  8303. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8304. this.bindUniformBuffer(uniformBuffer);
  8305. if (offset === undefined) {
  8306. offset = 0;
  8307. }
  8308. if (count === undefined) {
  8309. if (elements instanceof Float32Array) {
  8310. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8311. }
  8312. else {
  8313. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8314. }
  8315. }
  8316. else {
  8317. if (elements instanceof Float32Array) {
  8318. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8319. }
  8320. else {
  8321. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8322. }
  8323. }
  8324. this.bindUniformBuffer(null);
  8325. };
  8326. // VBOs
  8327. Engine.prototype._resetVertexBufferBinding = function () {
  8328. this.bindArrayBuffer(null);
  8329. this._cachedVertexBuffers = null;
  8330. };
  8331. Engine.prototype.createVertexBuffer = function (vertices) {
  8332. var vbo = this._gl.createBuffer();
  8333. this.bindArrayBuffer(vbo);
  8334. if (vertices instanceof Float32Array) {
  8335. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8336. }
  8337. else {
  8338. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8339. }
  8340. this._resetVertexBufferBinding();
  8341. vbo.references = 1;
  8342. return vbo;
  8343. };
  8344. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8345. var vbo = this._gl.createBuffer();
  8346. this.bindArrayBuffer(vbo);
  8347. if (vertices instanceof Float32Array) {
  8348. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8349. }
  8350. else {
  8351. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8352. }
  8353. this._resetVertexBufferBinding();
  8354. vbo.references = 1;
  8355. return vbo;
  8356. };
  8357. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8358. this.bindArrayBuffer(vertexBuffer);
  8359. if (offset === undefined) {
  8360. offset = 0;
  8361. }
  8362. if (count === undefined) {
  8363. if (vertices instanceof Float32Array) {
  8364. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8365. }
  8366. else {
  8367. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8368. }
  8369. }
  8370. else {
  8371. if (vertices instanceof Float32Array) {
  8372. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8373. }
  8374. else {
  8375. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8376. }
  8377. }
  8378. this._resetVertexBufferBinding();
  8379. };
  8380. Engine.prototype._resetIndexBufferBinding = function () {
  8381. this.bindIndexBuffer(null);
  8382. this._cachedIndexBuffer = null;
  8383. };
  8384. Engine.prototype.createIndexBuffer = function (indices) {
  8385. var vbo = this._gl.createBuffer();
  8386. this.bindIndexBuffer(vbo);
  8387. // Check for 32 bits indices
  8388. var arrayBuffer;
  8389. var need32Bits = false;
  8390. if (indices instanceof Uint16Array) {
  8391. arrayBuffer = indices;
  8392. }
  8393. else {
  8394. //check 32 bit support
  8395. if (this._caps.uintIndices) {
  8396. if (indices instanceof Uint32Array) {
  8397. arrayBuffer = indices;
  8398. need32Bits = true;
  8399. }
  8400. else {
  8401. //number[] or Int32Array, check if 32 bit is necessary
  8402. for (var index = 0; index < indices.length; index++) {
  8403. if (indices[index] > 65535) {
  8404. need32Bits = true;
  8405. break;
  8406. }
  8407. }
  8408. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8409. }
  8410. }
  8411. else {
  8412. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8413. arrayBuffer = new Uint16Array(indices);
  8414. }
  8415. }
  8416. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8417. this._resetIndexBufferBinding();
  8418. vbo.references = 1;
  8419. vbo.is32Bits = need32Bits;
  8420. return vbo;
  8421. };
  8422. Engine.prototype.bindArrayBuffer = function (buffer) {
  8423. if (!this._vaoRecordInProgress) {
  8424. this._unBindVertexArrayObject();
  8425. }
  8426. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8427. };
  8428. Engine.prototype.bindUniformBuffer = function (buffer) {
  8429. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  8430. };
  8431. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  8432. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  8433. };
  8434. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  8435. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  8436. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  8437. };
  8438. ;
  8439. Engine.prototype.bindIndexBuffer = function (buffer) {
  8440. if (!this._vaoRecordInProgress) {
  8441. this._unBindVertexArrayObject();
  8442. }
  8443. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8444. };
  8445. Engine.prototype.bindBuffer = function (buffer, target) {
  8446. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8447. this._gl.bindBuffer(target, buffer);
  8448. this._currentBoundBuffer[target] = buffer;
  8449. }
  8450. };
  8451. Engine.prototype.updateArrayBuffer = function (data) {
  8452. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8453. };
  8454. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8455. var pointer = this._currentBufferPointers[indx];
  8456. var changed = false;
  8457. if (!pointer) {
  8458. changed = true;
  8459. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  8460. }
  8461. else {
  8462. if (pointer.buffer !== buffer) {
  8463. pointer.buffer = buffer;
  8464. changed = true;
  8465. }
  8466. if (pointer.size !== size) {
  8467. pointer.size = size;
  8468. changed = true;
  8469. }
  8470. if (pointer.type !== type) {
  8471. pointer.type = type;
  8472. changed = true;
  8473. }
  8474. if (pointer.normalized !== normalized) {
  8475. pointer.normalized = normalized;
  8476. changed = true;
  8477. }
  8478. if (pointer.stride !== stride) {
  8479. pointer.stride = stride;
  8480. changed = true;
  8481. }
  8482. if (pointer.offset !== offset) {
  8483. pointer.offset = offset;
  8484. changed = true;
  8485. }
  8486. }
  8487. if (changed || this._vaoRecordInProgress) {
  8488. this.bindArrayBuffer(buffer);
  8489. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8490. }
  8491. };
  8492. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8493. if (indexBuffer == null) {
  8494. return;
  8495. }
  8496. if (this._cachedIndexBuffer !== indexBuffer) {
  8497. this._cachedIndexBuffer = indexBuffer;
  8498. this.bindIndexBuffer(indexBuffer);
  8499. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8500. }
  8501. };
  8502. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8503. var attributes = effect.getAttributesNames();
  8504. if (!this._vaoRecordInProgress) {
  8505. this._unBindVertexArrayObject();
  8506. }
  8507. this.unbindAllAttributes();
  8508. for (var index = 0; index < attributes.length; index++) {
  8509. var order = effect.getAttributeLocation(index);
  8510. if (order >= 0) {
  8511. var vertexBuffer = vertexBuffers[attributes[index]];
  8512. if (!vertexBuffer) {
  8513. continue;
  8514. }
  8515. this._gl.enableVertexAttribArray(order);
  8516. if (!this._vaoRecordInProgress) {
  8517. this._vertexAttribArraysEnabled[order] = true;
  8518. }
  8519. var buffer = vertexBuffer.getBuffer();
  8520. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8521. if (vertexBuffer.getIsInstanced()) {
  8522. this._gl.vertexAttribDivisor(order, 1);
  8523. if (!this._vaoRecordInProgress) {
  8524. this._currentInstanceLocations.push(order);
  8525. this._currentInstanceBuffers.push(buffer);
  8526. }
  8527. }
  8528. }
  8529. }
  8530. };
  8531. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8532. var vao = this._gl.createVertexArray();
  8533. this._vaoRecordInProgress = true;
  8534. this._gl.bindVertexArray(vao);
  8535. this._mustWipeVertexAttributes = true;
  8536. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8537. this.bindIndexBuffer(indexBuffer);
  8538. this._vaoRecordInProgress = false;
  8539. this._gl.bindVertexArray(null);
  8540. return vao;
  8541. };
  8542. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8543. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8544. this._cachedVertexArrayObject = vertexArrayObject;
  8545. this._gl.bindVertexArray(vertexArrayObject);
  8546. this._cachedVertexBuffers = null;
  8547. this._cachedIndexBuffer = null;
  8548. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8549. this._mustWipeVertexAttributes = true;
  8550. }
  8551. };
  8552. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  8553. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  8554. this._cachedVertexBuffers = vertexBuffer;
  8555. this._cachedEffectForVertexBuffers = effect;
  8556. var attributesCount = effect.getAttributesCount();
  8557. this._unBindVertexArrayObject();
  8558. this.unbindAllAttributes();
  8559. var offset = 0;
  8560. for (var index = 0; index < attributesCount; index++) {
  8561. if (index < vertexDeclaration.length) {
  8562. var order = effect.getAttributeLocation(index);
  8563. if (order >= 0) {
  8564. this._gl.enableVertexAttribArray(order);
  8565. this._vertexAttribArraysEnabled[order] = true;
  8566. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  8567. }
  8568. offset += vertexDeclaration[index] * 4;
  8569. }
  8570. }
  8571. }
  8572. this._bindIndexBufferWithCache(indexBuffer);
  8573. };
  8574. Engine.prototype._unBindVertexArrayObject = function () {
  8575. if (!this._cachedVertexArrayObject) {
  8576. return;
  8577. }
  8578. this._cachedVertexArrayObject = null;
  8579. this._gl.bindVertexArray(null);
  8580. };
  8581. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  8582. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  8583. this._cachedVertexBuffers = vertexBuffers;
  8584. this._cachedEffectForVertexBuffers = effect;
  8585. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8586. }
  8587. this._bindIndexBufferWithCache(indexBuffer);
  8588. };
  8589. Engine.prototype.unbindInstanceAttributes = function () {
  8590. var boundBuffer;
  8591. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  8592. var instancesBuffer = this._currentInstanceBuffers[i];
  8593. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  8594. boundBuffer = instancesBuffer;
  8595. this.bindArrayBuffer(instancesBuffer);
  8596. }
  8597. var offsetLocation = this._currentInstanceLocations[i];
  8598. this._gl.vertexAttribDivisor(offsetLocation, 0);
  8599. }
  8600. this._currentInstanceBuffers.length = 0;
  8601. this._currentInstanceLocations.length = 0;
  8602. };
  8603. Engine.prototype.releaseVertexArrayObject = function (vao) {
  8604. this._gl.deleteVertexArray(vao);
  8605. };
  8606. Engine.prototype._releaseBuffer = function (buffer) {
  8607. buffer.references--;
  8608. if (buffer.references === 0) {
  8609. this._gl.deleteBuffer(buffer);
  8610. return true;
  8611. }
  8612. return false;
  8613. };
  8614. Engine.prototype.createInstancesBuffer = function (capacity) {
  8615. var buffer = this._gl.createBuffer();
  8616. buffer.capacity = capacity;
  8617. this.bindArrayBuffer(buffer);
  8618. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  8619. return buffer;
  8620. };
  8621. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  8622. this._gl.deleteBuffer(buffer);
  8623. };
  8624. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  8625. this.bindArrayBuffer(instancesBuffer);
  8626. if (data) {
  8627. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8628. }
  8629. if (offsetLocations[0].index !== undefined) {
  8630. var stride = 0;
  8631. for (var i = 0; i < offsetLocations.length; i++) {
  8632. var ai = offsetLocations[i];
  8633. stride += ai.attributeSize * 4;
  8634. }
  8635. for (var i = 0; i < offsetLocations.length; i++) {
  8636. var ai = offsetLocations[i];
  8637. if (!this._vertexAttribArraysEnabled[ai.index]) {
  8638. this._gl.enableVertexAttribArray(ai.index);
  8639. this._vertexAttribArraysEnabled[ai.index] = true;
  8640. }
  8641. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  8642. this._gl.vertexAttribDivisor(ai.index, 1);
  8643. this._currentInstanceLocations.push(ai.index);
  8644. this._currentInstanceBuffers.push(instancesBuffer);
  8645. }
  8646. }
  8647. else {
  8648. for (var index = 0; index < 4; index++) {
  8649. var offsetLocation = offsetLocations[index];
  8650. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  8651. this._gl.enableVertexAttribArray(offsetLocation);
  8652. this._vertexAttribArraysEnabled[offsetLocation] = true;
  8653. }
  8654. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  8655. this._gl.vertexAttribDivisor(offsetLocation, 1);
  8656. this._currentInstanceLocations.push(offsetLocation);
  8657. this._currentInstanceBuffers.push(instancesBuffer);
  8658. }
  8659. }
  8660. };
  8661. Engine.prototype.applyStates = function () {
  8662. this._depthCullingState.apply(this._gl);
  8663. this._stencilState.apply(this._gl);
  8664. this._alphaState.apply(this._gl);
  8665. };
  8666. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  8667. // Apply states
  8668. this.applyStates();
  8669. this._drawCalls.addCount(1, false);
  8670. // Render
  8671. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  8672. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  8673. if (instancesCount) {
  8674. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  8675. return;
  8676. }
  8677. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  8678. };
  8679. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  8680. // Apply states
  8681. this.applyStates();
  8682. this._drawCalls.addCount(1, false);
  8683. if (instancesCount) {
  8684. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  8685. return;
  8686. }
  8687. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  8688. };
  8689. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  8690. // Apply states
  8691. this.applyStates();
  8692. this._drawCalls.addCount(1, false);
  8693. if (instancesCount) {
  8694. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  8695. return;
  8696. }
  8697. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  8698. };
  8699. // Shaders
  8700. Engine.prototype._releaseEffect = function (effect) {
  8701. if (this._compiledEffects[effect._key]) {
  8702. delete this._compiledEffects[effect._key];
  8703. if (effect.getProgram()) {
  8704. this._gl.deleteProgram(effect.getProgram());
  8705. }
  8706. }
  8707. };
  8708. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  8709. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  8710. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  8711. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  8712. if (this._compiledEffects[name]) {
  8713. return this._compiledEffects[name];
  8714. }
  8715. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  8716. effect._key = name;
  8717. this._compiledEffects[name] = effect;
  8718. return effect;
  8719. };
  8720. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  8721. if (uniformsNames === void 0) { uniformsNames = []; }
  8722. if (samplers === void 0) { samplers = []; }
  8723. if (defines === void 0) { defines = ""; }
  8724. return this.createEffect({
  8725. vertex: "particles",
  8726. fragmentElement: fragmentName
  8727. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  8728. };
  8729. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  8730. context = context || this._gl;
  8731. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  8732. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  8733. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  8734. var shaderProgram = context.createProgram();
  8735. context.attachShader(shaderProgram, vertexShader);
  8736. context.attachShader(shaderProgram, fragmentShader);
  8737. context.linkProgram(shaderProgram);
  8738. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  8739. if (!linked) {
  8740. var error = context.getProgramInfoLog(shaderProgram);
  8741. if (error) {
  8742. throw new Error(error);
  8743. }
  8744. }
  8745. context.deleteShader(vertexShader);
  8746. context.deleteShader(fragmentShader);
  8747. return shaderProgram;
  8748. };
  8749. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  8750. var results = [];
  8751. for (var index = 0; index < uniformsNames.length; index++) {
  8752. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  8753. }
  8754. return results;
  8755. };
  8756. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  8757. var results = [];
  8758. for (var index = 0; index < attributesNames.length; index++) {
  8759. try {
  8760. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  8761. }
  8762. catch (e) {
  8763. results.push(-1);
  8764. }
  8765. }
  8766. return results;
  8767. };
  8768. Engine.prototype.enableEffect = function (effect) {
  8769. // Use program
  8770. this.setProgram(effect.getProgram());
  8771. this._currentEffect = effect;
  8772. if (effect.onBind) {
  8773. effect.onBind(effect);
  8774. }
  8775. };
  8776. Engine.prototype.setIntArray = function (uniform, array) {
  8777. if (!uniform)
  8778. return;
  8779. this._gl.uniform1iv(uniform, array);
  8780. };
  8781. Engine.prototype.setIntArray2 = function (uniform, array) {
  8782. if (!uniform || array.length % 2 !== 0)
  8783. return;
  8784. this._gl.uniform2iv(uniform, array);
  8785. };
  8786. Engine.prototype.setIntArray3 = function (uniform, array) {
  8787. if (!uniform || array.length % 3 !== 0)
  8788. return;
  8789. this._gl.uniform3iv(uniform, array);
  8790. };
  8791. Engine.prototype.setIntArray4 = function (uniform, array) {
  8792. if (!uniform || array.length % 4 !== 0)
  8793. return;
  8794. this._gl.uniform4iv(uniform, array);
  8795. };
  8796. Engine.prototype.setFloatArray = function (uniform, array) {
  8797. if (!uniform)
  8798. return;
  8799. this._gl.uniform1fv(uniform, array);
  8800. };
  8801. Engine.prototype.setFloatArray2 = function (uniform, array) {
  8802. if (!uniform || array.length % 2 !== 0)
  8803. return;
  8804. this._gl.uniform2fv(uniform, array);
  8805. };
  8806. Engine.prototype.setFloatArray3 = function (uniform, array) {
  8807. if (!uniform || array.length % 3 !== 0)
  8808. return;
  8809. this._gl.uniform3fv(uniform, array);
  8810. };
  8811. Engine.prototype.setFloatArray4 = function (uniform, array) {
  8812. if (!uniform || array.length % 4 !== 0)
  8813. return;
  8814. this._gl.uniform4fv(uniform, array);
  8815. };
  8816. Engine.prototype.setArray = function (uniform, array) {
  8817. if (!uniform)
  8818. return;
  8819. this._gl.uniform1fv(uniform, array);
  8820. };
  8821. Engine.prototype.setArray2 = function (uniform, array) {
  8822. if (!uniform || array.length % 2 !== 0)
  8823. return;
  8824. this._gl.uniform2fv(uniform, array);
  8825. };
  8826. Engine.prototype.setArray3 = function (uniform, array) {
  8827. if (!uniform || array.length % 3 !== 0)
  8828. return;
  8829. this._gl.uniform3fv(uniform, array);
  8830. };
  8831. Engine.prototype.setArray4 = function (uniform, array) {
  8832. if (!uniform || array.length % 4 !== 0)
  8833. return;
  8834. this._gl.uniform4fv(uniform, array);
  8835. };
  8836. Engine.prototype.setMatrices = function (uniform, matrices) {
  8837. if (!uniform)
  8838. return;
  8839. this._gl.uniformMatrix4fv(uniform, false, matrices);
  8840. };
  8841. Engine.prototype.setMatrix = function (uniform, matrix) {
  8842. if (!uniform)
  8843. return;
  8844. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  8845. };
  8846. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  8847. if (!uniform)
  8848. return;
  8849. this._gl.uniformMatrix3fv(uniform, false, matrix);
  8850. };
  8851. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  8852. if (!uniform)
  8853. return;
  8854. this._gl.uniformMatrix2fv(uniform, false, matrix);
  8855. };
  8856. Engine.prototype.setFloat = function (uniform, value) {
  8857. if (!uniform)
  8858. return;
  8859. this._gl.uniform1f(uniform, value);
  8860. };
  8861. Engine.prototype.setFloat2 = function (uniform, x, y) {
  8862. if (!uniform)
  8863. return;
  8864. this._gl.uniform2f(uniform, x, y);
  8865. };
  8866. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  8867. if (!uniform)
  8868. return;
  8869. this._gl.uniform3f(uniform, x, y, z);
  8870. };
  8871. Engine.prototype.setBool = function (uniform, bool) {
  8872. if (!uniform)
  8873. return;
  8874. this._gl.uniform1i(uniform, bool);
  8875. };
  8876. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  8877. if (!uniform)
  8878. return;
  8879. this._gl.uniform4f(uniform, x, y, z, w);
  8880. };
  8881. Engine.prototype.setColor3 = function (uniform, color3) {
  8882. if (!uniform)
  8883. return;
  8884. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  8885. };
  8886. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  8887. if (!uniform)
  8888. return;
  8889. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  8890. };
  8891. // States
  8892. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  8893. if (zOffset === void 0) { zOffset = 0; }
  8894. if (reverseSide === void 0) { reverseSide = false; }
  8895. // Culling
  8896. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  8897. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  8898. var cullFace = this.cullBackFaces ? showSide : hideSide;
  8899. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  8900. if (culling) {
  8901. this._depthCullingState.cullFace = cullFace;
  8902. this._depthCullingState.cull = true;
  8903. }
  8904. else {
  8905. this._depthCullingState.cull = false;
  8906. }
  8907. }
  8908. // Z offset
  8909. this.setZOffset(zOffset);
  8910. };
  8911. Engine.prototype.setZOffset = function (value) {
  8912. this._depthCullingState.zOffset = value;
  8913. };
  8914. Engine.prototype.getZOffset = function () {
  8915. return this._depthCullingState.zOffset;
  8916. };
  8917. Engine.prototype.setDepthBuffer = function (enable) {
  8918. this._depthCullingState.depthTest = enable;
  8919. };
  8920. Engine.prototype.getDepthWrite = function () {
  8921. return this._depthCullingState.depthMask;
  8922. };
  8923. Engine.prototype.setDepthWrite = function (enable) {
  8924. this._depthCullingState.depthMask = enable;
  8925. };
  8926. Engine.prototype.setColorWrite = function (enable) {
  8927. this._gl.colorMask(enable, enable, enable, enable);
  8928. };
  8929. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  8930. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  8931. };
  8932. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  8933. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  8934. if (this._alphaMode === mode) {
  8935. return;
  8936. }
  8937. switch (mode) {
  8938. case Engine.ALPHA_DISABLE:
  8939. this._alphaState.alphaBlend = false;
  8940. break;
  8941. case Engine.ALPHA_PREMULTIPLIED:
  8942. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8943. this._alphaState.alphaBlend = true;
  8944. break;
  8945. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  8946. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  8947. this._alphaState.alphaBlend = true;
  8948. break;
  8949. case Engine.ALPHA_COMBINE:
  8950. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8951. this._alphaState.alphaBlend = true;
  8952. break;
  8953. case Engine.ALPHA_ONEONE:
  8954. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8955. this._alphaState.alphaBlend = true;
  8956. break;
  8957. case Engine.ALPHA_ADD:
  8958. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8959. this._alphaState.alphaBlend = true;
  8960. break;
  8961. case Engine.ALPHA_SUBTRACT:
  8962. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8963. this._alphaState.alphaBlend = true;
  8964. break;
  8965. case Engine.ALPHA_MULTIPLY:
  8966. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  8967. this._alphaState.alphaBlend = true;
  8968. break;
  8969. case Engine.ALPHA_MAXIMIZED:
  8970. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8971. this._alphaState.alphaBlend = true;
  8972. break;
  8973. case Engine.ALPHA_INTERPOLATE:
  8974. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  8975. this._alphaState.alphaBlend = true;
  8976. break;
  8977. case Engine.ALPHA_SCREENMODE:
  8978. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  8979. this._alphaState.alphaBlend = true;
  8980. break;
  8981. }
  8982. if (!noDepthWriteChange) {
  8983. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  8984. }
  8985. this._alphaMode = mode;
  8986. };
  8987. Engine.prototype.getAlphaMode = function () {
  8988. return this._alphaMode;
  8989. };
  8990. Engine.prototype.setAlphaTesting = function (enable) {
  8991. this._alphaTest = enable;
  8992. };
  8993. Engine.prototype.getAlphaTesting = function () {
  8994. return !!this._alphaTest;
  8995. };
  8996. // Textures
  8997. Engine.prototype.wipeCaches = function (bruteForce) {
  8998. if (this.preventCacheWipeBetweenFrames) {
  8999. return;
  9000. }
  9001. this.resetTextureCache();
  9002. this._currentEffect = null;
  9003. // 6/8/2017: deltakosh: Should not be required anymore.
  9004. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  9005. if (bruteForce) {
  9006. this._stencilState.reset();
  9007. this._depthCullingState.reset();
  9008. this.setDepthFunctionToLessOrEqual();
  9009. this._alphaState.reset();
  9010. }
  9011. this._cachedVertexBuffers = null;
  9012. this._cachedIndexBuffer = null;
  9013. this._cachedEffectForVertexBuffers = null;
  9014. this._unBindVertexArrayObject();
  9015. this.bindIndexBuffer(null);
  9016. this.bindArrayBuffer(null);
  9017. };
  9018. /**
  9019. * Set the compressed texture format to use, based on the formats you have, and the formats
  9020. * supported by the hardware / browser.
  9021. *
  9022. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9023. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9024. * to API arguments needed to compressed textures. This puts the burden on the container
  9025. * generator to house the arcane code for determining these for current & future formats.
  9026. *
  9027. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9028. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9029. *
  9030. * Note: The result of this call is not taken into account when a texture is base64.
  9031. *
  9032. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9033. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9034. *
  9035. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9036. * @returns The extension selected.
  9037. */
  9038. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9039. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9040. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9041. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9042. return this._textureFormatInUse = this._texturesSupported[i];
  9043. }
  9044. }
  9045. }
  9046. // actively set format to nothing, to allow this to be called more than once
  9047. // and possibly fail the 2nd time
  9048. return this._textureFormatInUse = null;
  9049. };
  9050. /**
  9051. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9052. * @param {string} urlArg- This contains one of the following:
  9053. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9054. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9055. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9056. *
  9057. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9058. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9059. * @param {Scene} scene- Needed for loading to the correct scene.
  9060. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9061. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9062. * @param {callback} onError- Optional callback to be called upon failure.
  9063. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9064. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9065. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9066. *
  9067. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9068. */
  9069. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9070. var _this = this;
  9071. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9072. if (onLoad === void 0) { onLoad = null; }
  9073. if (onError === void 0) { onError = null; }
  9074. if (buffer === void 0) { buffer = null; }
  9075. var texture = fallBack ? fallBack : this._gl.createTexture();
  9076. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9077. var fromData = url.substr(0, 5) === "data:";
  9078. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9079. // establish the file extension, if possible
  9080. var lastDot = url.lastIndexOf('.');
  9081. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9082. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9083. if (isDDS) {
  9084. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  9085. }
  9086. var isTGA = (extension === ".tga");
  9087. // determine if a ktx file should be substituted
  9088. var isKTX = false;
  9089. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9090. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9091. isKTX = true;
  9092. }
  9093. scene._addPendingData(texture);
  9094. texture.url = url;
  9095. texture.noMipmap = noMipmap;
  9096. texture.references = 1;
  9097. texture.samplingMode = samplingMode;
  9098. texture.onLoadedCallbacks = [];
  9099. if (onLoad) {
  9100. texture.onLoadedCallbacks.push(onLoad);
  9101. }
  9102. if (!fallBack)
  9103. this._loadedTexturesCache.push(texture);
  9104. var onerror = function () {
  9105. scene._removePendingData(texture);
  9106. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9107. if (isKTX) {
  9108. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9109. }
  9110. else if (onError) {
  9111. onError();
  9112. }
  9113. };
  9114. var callback;
  9115. // processing for non-image formats
  9116. if (isKTX || isTGA || isDDS) {
  9117. if (isKTX) {
  9118. callback = function (data) {
  9119. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9120. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9121. ktx.uploadLevels(_this._gl, !noMipmap);
  9122. }, samplingMode);
  9123. };
  9124. }
  9125. else if (isTGA) {
  9126. callback = function (arrayBuffer) {
  9127. var data = new Uint8Array(arrayBuffer);
  9128. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9129. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9130. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9131. }, samplingMode);
  9132. };
  9133. }
  9134. else if (isDDS) {
  9135. callback = function (data) {
  9136. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9137. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9138. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9139. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  9140. }, samplingMode);
  9141. };
  9142. }
  9143. if (!buffer) {
  9144. BABYLON.Tools.LoadFile(url, function (data) {
  9145. callback(data);
  9146. }, null, scene.database, true, onerror);
  9147. }
  9148. else {
  9149. callback(buffer);
  9150. }
  9151. // image format processing
  9152. }
  9153. else {
  9154. var onload = function (img) {
  9155. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  9156. var isPot = (img.width === potWidth && img.height === potHeight);
  9157. if (!isPot) {
  9158. _this._prepareWorkingCanvas();
  9159. _this._workingCanvas.width = potWidth;
  9160. _this._workingCanvas.height = potHeight;
  9161. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9162. _this._workingContext.imageSmoothingEnabled = false;
  9163. _this._workingContext.mozImageSmoothingEnabled = false;
  9164. _this._workingContext.oImageSmoothingEnabled = false;
  9165. _this._workingContext.webkitImageSmoothingEnabled = false;
  9166. _this._workingContext.msImageSmoothingEnabled = false;
  9167. }
  9168. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  9169. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9170. _this._workingContext.imageSmoothingEnabled = true;
  9171. _this._workingContext.mozImageSmoothingEnabled = true;
  9172. _this._workingContext.oImageSmoothingEnabled = true;
  9173. _this._workingContext.webkitImageSmoothingEnabled = true;
  9174. _this._workingContext.msImageSmoothingEnabled = true;
  9175. }
  9176. }
  9177. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? _this._gl.RGB : _this._gl.RGBA);
  9178. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  9179. }, samplingMode);
  9180. };
  9181. if (!fromData || isBase64)
  9182. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  9183. else if (buffer instanceof Array || typeof buffer === "string")
  9184. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  9185. else
  9186. onload(buffer);
  9187. }
  9188. return texture;
  9189. };
  9190. Engine.prototype._getInternalFormat = function (format) {
  9191. var internalFormat = this._gl.RGBA;
  9192. switch (format) {
  9193. case Engine.TEXTUREFORMAT_ALPHA:
  9194. internalFormat = this._gl.ALPHA;
  9195. break;
  9196. case Engine.TEXTUREFORMAT_LUMINANCE:
  9197. internalFormat = this._gl.LUMINANCE;
  9198. break;
  9199. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9200. internalFormat = this._gl.LUMINANCE_ALPHA;
  9201. break;
  9202. case Engine.TEXTUREFORMAT_RGB:
  9203. internalFormat = this._gl.RGB;
  9204. break;
  9205. case Engine.TEXTUREFORMAT_RGBA:
  9206. internalFormat = this._gl.RGBA;
  9207. break;
  9208. }
  9209. return internalFormat;
  9210. };
  9211. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9212. if (compression === void 0) { compression = null; }
  9213. var internalFormat = this._getInternalFormat(format);
  9214. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9215. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9216. if (texture._width % 4 !== 0) {
  9217. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9218. }
  9219. if (compression) {
  9220. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  9221. }
  9222. else {
  9223. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9224. }
  9225. if (texture.generateMipMaps) {
  9226. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9227. }
  9228. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9229. this.resetTextureCache();
  9230. texture.isReady = true;
  9231. };
  9232. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9233. if (compression === void 0) { compression = null; }
  9234. var texture = this._gl.createTexture();
  9235. texture._baseWidth = width;
  9236. texture._baseHeight = height;
  9237. texture._width = width;
  9238. texture._height = height;
  9239. texture.references = 1;
  9240. this.updateRawTexture(texture, data, format, invertY, compression);
  9241. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9242. // Filters
  9243. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9244. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9245. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9246. if (generateMipMaps) {
  9247. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9248. }
  9249. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9250. texture.samplingMode = samplingMode;
  9251. this._loadedTexturesCache.push(texture);
  9252. return texture;
  9253. };
  9254. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9255. var texture = this._gl.createTexture();
  9256. texture._baseWidth = width;
  9257. texture._baseHeight = height;
  9258. if (generateMipMaps) {
  9259. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  9260. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  9261. }
  9262. this.resetTextureCache();
  9263. texture._width = width;
  9264. texture._height = height;
  9265. texture.isReady = false;
  9266. texture.generateMipMaps = generateMipMaps;
  9267. texture.references = 1;
  9268. texture.samplingMode = samplingMode;
  9269. this.updateTextureSamplingMode(samplingMode, texture);
  9270. this._loadedTexturesCache.push(texture);
  9271. return texture;
  9272. };
  9273. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9274. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9275. if (texture.isCube) {
  9276. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9277. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9278. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9279. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9280. }
  9281. else {
  9282. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9283. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9284. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9285. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9286. }
  9287. texture.samplingMode = samplingMode;
  9288. };
  9289. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9290. if (premulAlpha === void 0) { premulAlpha = false; }
  9291. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9292. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9293. if (premulAlpha) {
  9294. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9295. }
  9296. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9297. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9298. if (texture.generateMipMaps) {
  9299. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9300. }
  9301. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9302. if (premulAlpha) {
  9303. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9304. }
  9305. this.resetTextureCache();
  9306. texture.isReady = true;
  9307. };
  9308. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9309. if (texture._isDisabled) {
  9310. return;
  9311. }
  9312. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9313. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9314. try {
  9315. // Testing video texture support
  9316. if (this._videoTextureSupported === undefined) {
  9317. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9318. if (this._gl.getError() !== 0) {
  9319. this._videoTextureSupported = false;
  9320. }
  9321. else {
  9322. this._videoTextureSupported = true;
  9323. }
  9324. }
  9325. // Copy video through the current working canvas if video texture is not supported
  9326. if (!this._videoTextureSupported) {
  9327. if (!texture._workingCanvas) {
  9328. texture._workingCanvas = document.createElement("canvas");
  9329. texture._workingContext = texture._workingCanvas.getContext("2d");
  9330. texture._workingCanvas.width = texture._width;
  9331. texture._workingCanvas.height = texture._height;
  9332. }
  9333. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  9334. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9335. }
  9336. else {
  9337. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9338. }
  9339. if (texture.generateMipMaps) {
  9340. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9341. }
  9342. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9343. this.resetTextureCache();
  9344. texture.isReady = true;
  9345. }
  9346. catch (ex) {
  9347. // Something unexpected
  9348. // Let's disable the texture
  9349. texture._isDisabled = true;
  9350. }
  9351. };
  9352. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9353. // old version had a "generateMipMaps" arg instead of options.
  9354. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9355. // in the same way, generateDepthBuffer is defaulted to true
  9356. var generateMipMaps = false;
  9357. var generateDepthBuffer = true;
  9358. var generateStencilBuffer = false;
  9359. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9360. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9361. if (options !== undefined) {
  9362. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9363. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9364. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9365. type = options.type === undefined ? type : options.type;
  9366. if (options.samplingMode !== undefined) {
  9367. samplingMode = options.samplingMode;
  9368. }
  9369. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9370. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9371. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9372. }
  9373. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9374. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9375. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9376. }
  9377. }
  9378. var gl = this._gl;
  9379. var texture = gl.createTexture();
  9380. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9381. var width = size.width || size;
  9382. var height = size.height || size;
  9383. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9384. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9385. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9386. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9387. }
  9388. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9389. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9390. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9391. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9392. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9393. // Create the framebuffer
  9394. var framebuffer = gl.createFramebuffer();
  9395. this.bindUnboundFramebuffer(framebuffer);
  9396. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9397. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9398. if (generateMipMaps) {
  9399. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9400. }
  9401. // Unbind
  9402. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9403. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9404. this.bindUnboundFramebuffer(null);
  9405. texture._framebuffer = framebuffer;
  9406. texture._baseWidth = width;
  9407. texture._baseHeight = height;
  9408. texture._width = width;
  9409. texture._height = height;
  9410. texture.isReady = true;
  9411. texture.samples = 1;
  9412. texture.generateMipMaps = generateMipMaps;
  9413. texture.references = 1;
  9414. texture.samplingMode = samplingMode;
  9415. texture.type = type;
  9416. texture._generateDepthBuffer = generateDepthBuffer;
  9417. texture._generateStencilBuffer = generateStencilBuffer;
  9418. this.resetTextureCache();
  9419. this._loadedTexturesCache.push(texture);
  9420. return texture;
  9421. };
  9422. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  9423. var generateMipMaps = false;
  9424. var generateDepthBuffer = true;
  9425. var generateStencilBuffer = false;
  9426. var generateDepthTexture = false;
  9427. var textureCount = 1;
  9428. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  9429. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9430. var types = [], samplingModes = [];
  9431. if (options !== undefined) {
  9432. generateMipMaps = options.generateMipMaps;
  9433. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9434. generateStencilBuffer = options.generateStencilBuffer;
  9435. generateDepthTexture = options.generateDepthTexture;
  9436. textureCount = options.textureCount || 1;
  9437. if (options.types) {
  9438. types = options.types;
  9439. }
  9440. if (options.samplingModes) {
  9441. samplingModes = options.samplingModes;
  9442. }
  9443. }
  9444. var gl = this._gl;
  9445. // Create the framebuffer
  9446. var framebuffer = gl.createFramebuffer();
  9447. this.bindUnboundFramebuffer(framebuffer);
  9448. var width = size.width || size;
  9449. var height = size.height || size;
  9450. var textures = [];
  9451. var attachments = [];
  9452. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9453. for (var i = 0; i < textureCount; i++) {
  9454. var samplingMode = samplingModes[i] || defaultSamplingMode;
  9455. var type = types[i] || defaultType;
  9456. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9457. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9458. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9459. }
  9460. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9461. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9462. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9463. }
  9464. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9465. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9466. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9467. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9468. }
  9469. var texture = gl.createTexture();
  9470. var attachment = gl["COLOR_ATTACHMENT" + i];
  9471. textures.push(texture);
  9472. attachments.push(attachment);
  9473. gl.activeTexture(gl["TEXTURE" + i]);
  9474. gl.bindTexture(gl.TEXTURE_2D, texture);
  9475. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9476. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9477. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9478. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9479. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9480. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture, 0);
  9481. if (generateMipMaps) {
  9482. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9483. }
  9484. // Unbind
  9485. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9486. texture._framebuffer = framebuffer;
  9487. texture._depthStencilBuffer = depthStencilBuffer;
  9488. texture._baseWidth = width;
  9489. texture._baseHeight = height;
  9490. texture._width = width;
  9491. texture._height = height;
  9492. texture.isReady = true;
  9493. texture.samples = 1;
  9494. texture.generateMipMaps = generateMipMaps;
  9495. texture.references = 1;
  9496. texture.samplingMode = samplingMode;
  9497. texture.type = type;
  9498. texture._generateDepthBuffer = generateDepthBuffer;
  9499. texture._generateStencilBuffer = generateStencilBuffer;
  9500. this._loadedTexturesCache.push(texture);
  9501. }
  9502. if (generateDepthTexture) {
  9503. // Depth texture
  9504. var depthTexture = gl.createTexture();
  9505. gl.activeTexture(gl.TEXTURE0);
  9506. gl.bindTexture(gl.TEXTURE_2D, depthTexture);
  9507. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9508. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9509. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9510. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9511. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  9512. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture, 0);
  9513. depthTexture._framebuffer = framebuffer;
  9514. depthTexture._baseWidth = width;
  9515. depthTexture._baseHeight = height;
  9516. depthTexture._width = width;
  9517. depthTexture._height = height;
  9518. depthTexture.isReady = true;
  9519. depthTexture.samples = 1;
  9520. depthTexture.generateMipMaps = generateMipMaps;
  9521. depthTexture.references = 1;
  9522. depthTexture.samplingMode = gl.NEAREST;
  9523. depthTexture._generateDepthBuffer = generateDepthBuffer;
  9524. depthTexture._generateStencilBuffer = generateStencilBuffer;
  9525. textures.push(depthTexture);
  9526. this._loadedTexturesCache.push(depthTexture);
  9527. }
  9528. gl.drawBuffers(attachments);
  9529. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9530. this.bindUnboundFramebuffer(null);
  9531. this.resetTextureCache();
  9532. return textures;
  9533. };
  9534. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  9535. if (samples === void 0) { samples = 1; }
  9536. var depthStencilBuffer = null;
  9537. var gl = this._gl;
  9538. // Create the depth/stencil buffer
  9539. if (generateStencilBuffer) {
  9540. depthStencilBuffer = gl.createRenderbuffer();
  9541. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9542. if (samples > 1) {
  9543. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_STENCIL, width, height);
  9544. }
  9545. else {
  9546. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9547. }
  9548. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9549. }
  9550. else if (generateDepthBuffer) {
  9551. depthStencilBuffer = gl.createRenderbuffer();
  9552. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9553. if (samples > 1) {
  9554. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  9555. }
  9556. else {
  9557. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9558. }
  9559. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9560. }
  9561. return depthStencilBuffer;
  9562. };
  9563. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  9564. if (this.webGLVersion < 2) {
  9565. return 1;
  9566. }
  9567. if (texture.samples === samples) {
  9568. return samples;
  9569. }
  9570. var gl = this._gl;
  9571. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  9572. // Dispose previous render buffers
  9573. if (texture._depthStencilBuffer) {
  9574. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9575. }
  9576. if (texture._MSAAFramebuffer) {
  9577. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9578. }
  9579. if (texture._MSAARenderBuffer) {
  9580. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9581. }
  9582. if (samples > 1) {
  9583. texture._MSAAFramebuffer = gl.createFramebuffer();
  9584. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  9585. var colorRenderbuffer = gl.createRenderbuffer();
  9586. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9587. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  9588. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9589. texture._MSAARenderBuffer = colorRenderbuffer;
  9590. }
  9591. else {
  9592. this.bindUnboundFramebuffer(texture._framebuffer);
  9593. }
  9594. texture.samples = samples;
  9595. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  9596. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9597. this.bindUnboundFramebuffer(null);
  9598. return samples;
  9599. };
  9600. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  9601. var gl = this._gl;
  9602. var texture = gl.createTexture();
  9603. var generateMipMaps = true;
  9604. var generateDepthBuffer = true;
  9605. var generateStencilBuffer = false;
  9606. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9607. if (options !== undefined) {
  9608. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9609. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9610. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9611. if (options.samplingMode !== undefined) {
  9612. samplingMode = options.samplingMode;
  9613. }
  9614. }
  9615. texture.isCube = true;
  9616. texture.references = 1;
  9617. texture.generateMipMaps = generateMipMaps;
  9618. texture.references = 1;
  9619. texture.samples = 1;
  9620. texture.samplingMode = samplingMode;
  9621. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9622. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9623. for (var face = 0; face < 6; face++) {
  9624. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  9625. }
  9626. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9627. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9628. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9629. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9630. // Create the framebuffer
  9631. var framebuffer = gl.createFramebuffer();
  9632. this.bindUnboundFramebuffer(framebuffer);
  9633. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  9634. // Mipmaps
  9635. if (texture.generateMipMaps) {
  9636. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9637. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9638. }
  9639. // Unbind
  9640. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9641. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9642. this.bindUnboundFramebuffer(null);
  9643. texture._framebuffer = framebuffer;
  9644. texture._width = size;
  9645. texture._height = size;
  9646. texture.isReady = true;
  9647. this.resetTextureCache();
  9648. this._loadedTexturesCache.push(texture);
  9649. return texture;
  9650. };
  9651. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format) {
  9652. var _this = this;
  9653. if (onLoad === void 0) { onLoad = null; }
  9654. if (onError === void 0) { onError = null; }
  9655. var gl = this._gl;
  9656. var texture = gl.createTexture();
  9657. texture.isCube = true;
  9658. texture.url = rootUrl;
  9659. texture.references = 1;
  9660. texture.onLoadedCallbacks = [];
  9661. var isKTX = false;
  9662. var lastDot = rootUrl.lastIndexOf('.');
  9663. var extension = rootUrl.substring(lastDot).toLowerCase();
  9664. if (this._textureFormatInUse) {
  9665. extension = this._textureFormatInUse;
  9666. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  9667. isKTX = true;
  9668. }
  9669. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9670. if (isDDS) {
  9671. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  9672. }
  9673. if (isKTX) {
  9674. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9675. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  9676. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  9677. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9678. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9679. ktx.uploadLevels(_this._gl, !noMipmap);
  9680. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9681. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9682. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9683. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9684. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9685. _this.resetTextureCache();
  9686. texture._width = ktx.pixelWidth;
  9687. texture._height = ktx.pixelHeight;
  9688. texture.isReady = true;
  9689. }, null, null, true, onError);
  9690. }
  9691. else if (isDDS) {
  9692. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9693. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9694. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  9695. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9696. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9697. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  9698. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  9699. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9700. }
  9701. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9702. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9703. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9704. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9705. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9706. _this.resetTextureCache();
  9707. texture._width = info.width;
  9708. texture._height = info.height;
  9709. texture.isReady = true;
  9710. }, null, null, true, onError);
  9711. }
  9712. else {
  9713. cascadeLoad(rootUrl, scene, function (imgs) {
  9714. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  9715. var height = width;
  9716. _this._prepareWorkingCanvas();
  9717. _this._workingCanvas.width = width;
  9718. _this._workingCanvas.height = height;
  9719. var faces = [
  9720. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9721. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9722. ];
  9723. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9724. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9725. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  9726. for (var index = 0; index < faces.length; index++) {
  9727. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  9728. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  9729. }
  9730. if (!noMipmap) {
  9731. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9732. }
  9733. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9734. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  9735. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9736. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9737. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9738. _this.resetTextureCache();
  9739. texture._width = width;
  9740. texture._height = height;
  9741. texture.isReady = true;
  9742. texture.onLoadedCallbacks.forEach(function (callback) {
  9743. callback();
  9744. });
  9745. if (onLoad) {
  9746. onLoad();
  9747. }
  9748. }, files, onError);
  9749. }
  9750. this._loadedTexturesCache.push(texture);
  9751. return texture;
  9752. };
  9753. Engine.prototype.updateTextureSize = function (texture, width, height) {
  9754. texture._width = width;
  9755. texture._height = height;
  9756. texture._size = width * height;
  9757. texture._baseWidth = width;
  9758. texture._baseHeight = height;
  9759. };
  9760. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  9761. if (compression === void 0) { compression = null; }
  9762. if (level === void 0) { level = 0; }
  9763. var gl = this._gl;
  9764. var textureType = this._getWebGLTextureType(type);
  9765. var internalFormat = this._getInternalFormat(format);
  9766. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9767. var needConversion = false;
  9768. if (internalFormat === gl.RGB) {
  9769. internalFormat = gl.RGBA;
  9770. needConversion = true;
  9771. }
  9772. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9773. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9774. if (texture._width % 4 !== 0) {
  9775. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  9776. }
  9777. var facesIndex = [
  9778. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9779. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9780. ];
  9781. // Data are known to be in +X +Y +Z -X -Y -Z
  9782. for (var index = 0; index < facesIndex.length; index++) {
  9783. var faceData = data[index];
  9784. if (compression) {
  9785. gl.compressedTexImage2D(facesIndex[index], level, this.getCaps().s3tc[compression], texture._width, texture._height, 0, faceData);
  9786. }
  9787. else {
  9788. if (needConversion) {
  9789. faceData = this._convertRGBtoRGBATextureData(faceData, texture._width, texture._height, type);
  9790. }
  9791. gl.texImage2D(facesIndex[index], level, internalSizedFomat, texture._width, texture._height, 0, internalFormat, textureType, faceData);
  9792. }
  9793. }
  9794. var isPot = (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  9795. if (isPot && texture.generateMipMaps && level === 0) {
  9796. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  9797. }
  9798. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9799. this.resetTextureCache();
  9800. texture.isReady = true;
  9801. };
  9802. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  9803. if (compression === void 0) { compression = null; }
  9804. var gl = this._gl;
  9805. var texture = gl.createTexture();
  9806. texture.isCube = true;
  9807. texture.references = 1;
  9808. var textureType = this._getWebGLTextureType(type);
  9809. var internalFormat = this._getInternalFormat(format);
  9810. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9811. var needConversion = false;
  9812. if (internalFormat === gl.RGB) {
  9813. internalFormat = gl.RGBA;
  9814. needConversion = true;
  9815. }
  9816. var width = size;
  9817. var height = width;
  9818. texture._width = width;
  9819. texture._height = height;
  9820. // Double check on POT to generate Mips.
  9821. var isPot = (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  9822. if (!isPot) {
  9823. generateMipMaps = false;
  9824. }
  9825. texture.generateMipMaps = generateMipMaps;
  9826. // Upload data if needed. The texture won t be ready until then.
  9827. if (data) {
  9828. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  9829. }
  9830. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9831. // Filters
  9832. if (data && generateMipMaps) {
  9833. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  9834. }
  9835. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  9836. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9837. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9838. }
  9839. else if (textureType === Engine.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  9840. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9841. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9842. }
  9843. else {
  9844. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9845. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9846. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9847. }
  9848. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9849. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9850. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9851. this._loadedTexturesCache.push(texture);
  9852. return texture;
  9853. };
  9854. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  9855. var _this = this;
  9856. if (onLoad === void 0) { onLoad = null; }
  9857. if (onError === void 0) { onError = null; }
  9858. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9859. if (invertY === void 0) { invertY = false; }
  9860. var gl = this._gl;
  9861. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  9862. scene._addPendingData(texture);
  9863. texture.url = url;
  9864. var onerror = function () {
  9865. scene._removePendingData(texture);
  9866. if (onError) {
  9867. onError();
  9868. }
  9869. };
  9870. var internalCallback = function (data) {
  9871. var rgbeDataArrays = callback(data);
  9872. var facesIndex = [
  9873. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9874. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9875. ];
  9876. var width = texture._width;
  9877. var height = texture._height;
  9878. if (mipmmapGenerator) {
  9879. // TODO Remove this once Proper CubeMap Blur... This has nothing to do in engine...
  9880. // I ll remove ASAP.
  9881. var textureType = _this._getWebGLTextureType(type);
  9882. var internalFormat = _this._getInternalFormat(format);
  9883. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  9884. var needConversion = false;
  9885. if (internalFormat === gl.RGB) {
  9886. internalFormat = gl.RGBA;
  9887. needConversion = true;
  9888. }
  9889. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9890. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9891. var arrayTemp = [];
  9892. // Data are known to be in +X +Y +Z -X -Y -Z
  9893. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  9894. arrayTemp.push(rgbeDataArrays[0]); // +X
  9895. arrayTemp.push(rgbeDataArrays[3]); // -X
  9896. arrayTemp.push(rgbeDataArrays[1]); // +Y
  9897. arrayTemp.push(rgbeDataArrays[4]); // -Y
  9898. arrayTemp.push(rgbeDataArrays[2]); // +Z
  9899. arrayTemp.push(rgbeDataArrays[5]); // -Z
  9900. var mipData = mipmmapGenerator(arrayTemp);
  9901. // mipData is order in +X -X +Y -Y +Z -Z
  9902. var mipFaces = [0, 2, 4, 1, 3, 5];
  9903. for (var level = 0; level < mipData.length; level++) {
  9904. var mipSize = width >> level;
  9905. for (var mipIndex in mipFaces) {
  9906. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  9907. if (needConversion) {
  9908. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  9909. }
  9910. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  9911. }
  9912. }
  9913. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9914. }
  9915. else {
  9916. texture.generateMipMaps = !noMipmap;
  9917. _this.updateRawCubeTexture(texture, rgbeDataArrays, format, type, invertY);
  9918. }
  9919. texture.isReady = true;
  9920. _this.resetTextureCache();
  9921. scene._removePendingData(texture);
  9922. if (onLoad) {
  9923. onLoad();
  9924. }
  9925. };
  9926. BABYLON.Tools.LoadFile(url, function (data) {
  9927. internalCallback(data);
  9928. }, onerror, scene.database, true);
  9929. return texture;
  9930. };
  9931. ;
  9932. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  9933. // Create new RGBA data container.
  9934. var rgbaData;
  9935. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  9936. rgbaData = new Float32Array(width * height * 4);
  9937. }
  9938. else {
  9939. rgbaData = new Uint32Array(width * height * 4);
  9940. }
  9941. // Convert each pixel.
  9942. for (var x = 0; x < width; x++) {
  9943. for (var y = 0; y < height; y++) {
  9944. var index = (y * width + x) * 3;
  9945. var newIndex = (y * width + x) * 4;
  9946. // Map Old Value to new value.
  9947. rgbaData[newIndex + 0] = rgbData[index + 0];
  9948. rgbaData[newIndex + 1] = rgbData[index + 1];
  9949. rgbaData[newIndex + 2] = rgbData[index + 2];
  9950. // Add fully opaque alpha channel.
  9951. rgbaData[newIndex + 3] = 1;
  9952. }
  9953. }
  9954. return rgbaData;
  9955. };
  9956. Engine.prototype._releaseTexture = function (texture) {
  9957. var gl = this._gl;
  9958. if (texture._framebuffer) {
  9959. gl.deleteFramebuffer(texture._framebuffer);
  9960. }
  9961. if (texture._depthStencilBuffer) {
  9962. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9963. }
  9964. if (texture._MSAAFramebuffer) {
  9965. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9966. }
  9967. if (texture._MSAARenderBuffer) {
  9968. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9969. }
  9970. gl.deleteTexture(texture);
  9971. // Unbind channels
  9972. this.unbindAllTextures();
  9973. var index = this._loadedTexturesCache.indexOf(texture);
  9974. if (index !== -1) {
  9975. this._loadedTexturesCache.splice(index, 1);
  9976. }
  9977. };
  9978. Engine.prototype.setProgram = function (program) {
  9979. if (this._currentProgram !== program) {
  9980. this._gl.useProgram(program);
  9981. this._currentProgram = program;
  9982. }
  9983. };
  9984. Engine.prototype.bindSamplers = function (effect) {
  9985. this.setProgram(effect.getProgram());
  9986. var samplers = effect.getSamplers();
  9987. for (var index = 0; index < samplers.length; index++) {
  9988. var uniform = effect.getUniform(samplers[index]);
  9989. this._gl.uniform1i(uniform, index);
  9990. }
  9991. this._currentEffect = null;
  9992. };
  9993. Engine.prototype.activateTexture = function (texture) {
  9994. if (this._activeTexture !== texture) {
  9995. this._gl.activeTexture(texture);
  9996. this._activeTexture = texture;
  9997. }
  9998. };
  9999. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10000. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10001. this._gl.bindTexture(target, texture);
  10002. this._activeTexturesCache[this._activeTexture] = texture;
  10003. }
  10004. };
  10005. Engine.prototype._bindTexture = function (channel, texture) {
  10006. if (channel < 0) {
  10007. return;
  10008. }
  10009. this.activateTexture(this._gl.TEXTURE0 + channel);
  10010. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10011. };
  10012. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10013. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10014. };
  10015. Engine.prototype.unbindAllTextures = function () {
  10016. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10017. this.activateTexture(this._gl["TEXTURE" + channel]);
  10018. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10019. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10020. }
  10021. };
  10022. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10023. if (channel < 0) {
  10024. return;
  10025. }
  10026. this._gl.uniform1i(uniform, channel);
  10027. this._setTexture(channel, texture);
  10028. };
  10029. Engine.prototype._setTexture = function (channel, texture) {
  10030. // Not ready?
  10031. if (!texture) {
  10032. if (this._activeTexturesCache[channel] != null) {
  10033. this.activateTexture(this._gl["TEXTURE" + channel]);
  10034. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10035. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10036. }
  10037. return;
  10038. }
  10039. // Video
  10040. var alreadyActivated = false;
  10041. if (texture.video) {
  10042. this.activateTexture(this._gl["TEXTURE" + channel]);
  10043. alreadyActivated = true;
  10044. texture.update();
  10045. }
  10046. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10047. texture.delayLoad();
  10048. return;
  10049. }
  10050. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  10051. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  10052. if (this._activeTexturesCache[channel] === internalTexture) {
  10053. return;
  10054. }
  10055. if (!alreadyActivated) {
  10056. this.activateTexture(this._gl["TEXTURE" + channel]);
  10057. }
  10058. if (internalTexture.isCube) {
  10059. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10060. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10061. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10062. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10063. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10064. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10065. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10066. }
  10067. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10068. }
  10069. else {
  10070. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10071. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10072. internalTexture._cachedWrapU = texture.wrapU;
  10073. switch (texture.wrapU) {
  10074. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10075. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10076. break;
  10077. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10078. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10079. break;
  10080. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10081. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10082. break;
  10083. }
  10084. }
  10085. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10086. internalTexture._cachedWrapV = texture.wrapV;
  10087. switch (texture.wrapV) {
  10088. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10089. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10090. break;
  10091. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10092. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10093. break;
  10094. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10095. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10096. break;
  10097. }
  10098. }
  10099. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10100. }
  10101. };
  10102. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10103. if (channel < 0) {
  10104. return;
  10105. }
  10106. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10107. this._textureUnits = new Int32Array(textures.length);
  10108. }
  10109. for (var i = 0; i < textures.length; i++) {
  10110. this._textureUnits[i] = channel + i;
  10111. }
  10112. this._gl.uniform1iv(uniform, this._textureUnits);
  10113. for (var index = 0; index < textures.length; index++) {
  10114. this._setTexture(channel + index, textures[index]);
  10115. }
  10116. };
  10117. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10118. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10119. var value = texture.anisotropicFilteringLevel;
  10120. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10121. value = 1;
  10122. }
  10123. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  10124. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10125. texture._cachedAnisotropicFilteringLevel = value;
  10126. }
  10127. };
  10128. Engine.prototype.readPixels = function (x, y, width, height) {
  10129. var data = new Uint8Array(height * width * 4);
  10130. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10131. return data;
  10132. };
  10133. /**
  10134. * Add an externaly attached data from its key.
  10135. * This method call will fail and return false, if such key already exists.
  10136. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10137. * @param key the unique key that identifies the data
  10138. * @param data the data object to associate to the key for this Engine instance
  10139. * @return true if no such key were already present and the data was added successfully, false otherwise
  10140. */
  10141. Engine.prototype.addExternalData = function (key, data) {
  10142. if (!this._externalData) {
  10143. this._externalData = new BABYLON.StringDictionary();
  10144. }
  10145. return this._externalData.add(key, data);
  10146. };
  10147. /**
  10148. * Get an externaly attached data from its key
  10149. * @param key the unique key that identifies the data
  10150. * @return the associated data, if present (can be null), or undefined if not present
  10151. */
  10152. Engine.prototype.getExternalData = function (key) {
  10153. if (!this._externalData) {
  10154. this._externalData = new BABYLON.StringDictionary();
  10155. }
  10156. return this._externalData.get(key);
  10157. };
  10158. /**
  10159. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10160. * @param key the unique key that identifies the data
  10161. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10162. * @return the associated data, can be null if the factory returned null.
  10163. */
  10164. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10165. if (!this._externalData) {
  10166. this._externalData = new BABYLON.StringDictionary();
  10167. }
  10168. return this._externalData.getOrAddWithFactory(key, factory);
  10169. };
  10170. /**
  10171. * Remove an externaly attached data from the Engine instance
  10172. * @param key the unique key that identifies the data
  10173. * @return true if the data was successfully removed, false if it doesn't exist
  10174. */
  10175. Engine.prototype.removeExternalData = function (key) {
  10176. if (!this._externalData) {
  10177. this._externalData = new BABYLON.StringDictionary();
  10178. }
  10179. return this._externalData.remove(key);
  10180. };
  10181. Engine.prototype.releaseInternalTexture = function (texture) {
  10182. if (!texture) {
  10183. return;
  10184. }
  10185. texture.references--;
  10186. // Final reference ?
  10187. if (texture.references === 0) {
  10188. var texturesCache = this.getLoadedTexturesCache();
  10189. var index = texturesCache.indexOf(texture);
  10190. if (index > -1) {
  10191. texturesCache.splice(index, 1);
  10192. }
  10193. this._releaseTexture(texture);
  10194. }
  10195. };
  10196. Engine.prototype.unbindAllAttributes = function () {
  10197. if (this._mustWipeVertexAttributes) {
  10198. this._mustWipeVertexAttributes = false;
  10199. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10200. this._gl.disableVertexAttribArray(i);
  10201. this._vertexAttribArraysEnabled[i] = false;
  10202. this._currentBufferPointers[i] = null;
  10203. }
  10204. return;
  10205. }
  10206. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10207. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10208. continue;
  10209. }
  10210. this._gl.disableVertexAttribArray(i);
  10211. this._vertexAttribArraysEnabled[i] = false;
  10212. this._currentBufferPointers[i] = null;
  10213. }
  10214. };
  10215. Engine.prototype.releaseEffects = function () {
  10216. for (var name in this._compiledEffects) {
  10217. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10218. }
  10219. this._compiledEffects = {};
  10220. };
  10221. // Dispose
  10222. Engine.prototype.dispose = function () {
  10223. this.hideLoadingUI();
  10224. this.stopRenderLoop();
  10225. // Empty texture
  10226. if (this._emptyTexture) {
  10227. this._releaseTexture(this._emptyTexture);
  10228. this._emptyTexture = null;
  10229. }
  10230. if (this._emptyCubeTexture) {
  10231. this._releaseTexture(this._emptyCubeTexture);
  10232. this._emptyCubeTexture = null;
  10233. }
  10234. // Release scenes
  10235. while (this.scenes.length) {
  10236. this.scenes[0].dispose();
  10237. }
  10238. // Release audio engine
  10239. if (Engine.audioEngine) {
  10240. Engine.audioEngine.dispose();
  10241. }
  10242. // Release effects
  10243. this.releaseEffects();
  10244. // Unbind
  10245. this.unbindAllAttributes();
  10246. this._gl = null;
  10247. //WebVR
  10248. this.disableVR();
  10249. // Events
  10250. window.removeEventListener("blur", this._onBlur);
  10251. window.removeEventListener("focus", this._onFocus);
  10252. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  10253. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10254. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10255. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10256. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10257. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10258. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10259. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10260. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10261. // Remove from Instances
  10262. var index = Engine.Instances.indexOf(this);
  10263. if (index >= 0) {
  10264. Engine.Instances.splice(index, 1);
  10265. }
  10266. };
  10267. // Loading screen
  10268. Engine.prototype.displayLoadingUI = function () {
  10269. var loadingScreen = this.loadingScreen;
  10270. if (loadingScreen) {
  10271. loadingScreen.displayLoadingUI();
  10272. }
  10273. };
  10274. Engine.prototype.hideLoadingUI = function () {
  10275. var loadingScreen = this.loadingScreen;
  10276. if (loadingScreen) {
  10277. loadingScreen.hideLoadingUI();
  10278. }
  10279. };
  10280. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10281. get: function () {
  10282. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  10283. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  10284. return this._loadingScreen;
  10285. },
  10286. set: function (loadingScreen) {
  10287. this._loadingScreen = loadingScreen;
  10288. },
  10289. enumerable: true,
  10290. configurable: true
  10291. });
  10292. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10293. set: function (text) {
  10294. this.loadingScreen.loadingUIText = text;
  10295. },
  10296. enumerable: true,
  10297. configurable: true
  10298. });
  10299. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10300. set: function (color) {
  10301. this.loadingScreen.loadingUIBackgroundColor = color;
  10302. },
  10303. enumerable: true,
  10304. configurable: true
  10305. });
  10306. Engine.prototype.attachContextLostEvent = function (callback) {
  10307. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10308. };
  10309. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10310. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10311. };
  10312. Engine.prototype.getVertexShaderSource = function (program) {
  10313. var shaders = this._gl.getAttachedShaders(program);
  10314. return this._gl.getShaderSource(shaders[0]);
  10315. };
  10316. Engine.prototype.getFragmentShaderSource = function (program) {
  10317. var shaders = this._gl.getAttachedShaders(program);
  10318. return this._gl.getShaderSource(shaders[1]);
  10319. };
  10320. Engine.prototype.getError = function () {
  10321. return this._gl.getError();
  10322. };
  10323. // FPS
  10324. Engine.prototype.getFps = function () {
  10325. return this.fps;
  10326. };
  10327. Engine.prototype.getDeltaTime = function () {
  10328. return this.deltaTime;
  10329. };
  10330. Engine.prototype._measureFps = function () {
  10331. this.previousFramesDuration.push(BABYLON.Tools.Now);
  10332. var length = this.previousFramesDuration.length;
  10333. if (length >= 2) {
  10334. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  10335. }
  10336. if (length >= this.fpsRange) {
  10337. if (length > this.fpsRange) {
  10338. this.previousFramesDuration.splice(0, 1);
  10339. length = this.previousFramesDuration.length;
  10340. }
  10341. var sum = 0;
  10342. for (var id = 0; id < length - 1; id++) {
  10343. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  10344. }
  10345. this.fps = 1000.0 / (sum / (length - 1));
  10346. }
  10347. };
  10348. Engine.prototype._canRenderToFloatFramebuffer = function () {
  10349. if (this._webGLVersion > 1) {
  10350. return this._caps.colorBufferFloat;
  10351. }
  10352. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  10353. };
  10354. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  10355. if (this._webGLVersion > 1) {
  10356. return this._caps.colorBufferFloat;
  10357. }
  10358. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  10359. };
  10360. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  10361. Engine.prototype._canRenderToFramebuffer = function (type) {
  10362. var gl = this._gl;
  10363. //clear existing errors
  10364. while (gl.getError() !== gl.NO_ERROR) { }
  10365. var successful = true;
  10366. var texture = gl.createTexture();
  10367. gl.bindTexture(gl.TEXTURE_2D, texture);
  10368. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10369. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10370. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10371. var fb = gl.createFramebuffer();
  10372. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  10373. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10374. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  10375. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  10376. successful = successful && (gl.getError() === gl.NO_ERROR);
  10377. //try render by clearing frame buffer's color buffer
  10378. if (successful) {
  10379. gl.clear(gl.COLOR_BUFFER_BIT);
  10380. successful = successful && (gl.getError() === gl.NO_ERROR);
  10381. }
  10382. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  10383. if (successful) {
  10384. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  10385. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10386. var readFormat = gl.RGBA;
  10387. var readType = gl.UNSIGNED_BYTE;
  10388. var buffer = new Uint8Array(4);
  10389. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  10390. successful = successful && (gl.getError() === gl.NO_ERROR);
  10391. }
  10392. //clean up
  10393. gl.deleteTexture(texture);
  10394. gl.deleteFramebuffer(fb);
  10395. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10396. //clear accumulated errors
  10397. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  10398. return successful;
  10399. };
  10400. Engine.prototype._getWebGLTextureType = function (type) {
  10401. if (type === Engine.TEXTURETYPE_FLOAT) {
  10402. return this._gl.FLOAT;
  10403. }
  10404. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10405. // Add Half Float Constant.
  10406. return Engine.HALF_FLOAT_OES;
  10407. }
  10408. return this._gl.UNSIGNED_BYTE;
  10409. };
  10410. ;
  10411. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  10412. if (this._webGLVersion === 1) {
  10413. return this._gl.RGBA;
  10414. }
  10415. if (type === Engine.TEXTURETYPE_FLOAT) {
  10416. return Engine.RGBA32F;
  10417. }
  10418. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10419. return Engine.RGBA16F;
  10420. }
  10421. return this._gl.RGBA;
  10422. };
  10423. ;
  10424. // Statics
  10425. Engine.isSupported = function () {
  10426. try {
  10427. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  10428. if (navigator.isCocoonJS) {
  10429. return true;
  10430. }
  10431. var tempcanvas = document.createElement("canvas");
  10432. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  10433. return gl != null && !!window.WebGLRenderingContext;
  10434. }
  10435. catch (e) {
  10436. return false;
  10437. }
  10438. };
  10439. return Engine;
  10440. }());
  10441. Engine.Instances = new Array();
  10442. // Const statics
  10443. Engine._ALPHA_DISABLE = 0;
  10444. Engine._ALPHA_ADD = 1;
  10445. Engine._ALPHA_COMBINE = 2;
  10446. Engine._ALPHA_SUBTRACT = 3;
  10447. Engine._ALPHA_MULTIPLY = 4;
  10448. Engine._ALPHA_MAXIMIZED = 5;
  10449. Engine._ALPHA_ONEONE = 6;
  10450. Engine._ALPHA_PREMULTIPLIED = 7;
  10451. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  10452. Engine._ALPHA_INTERPOLATE = 9;
  10453. Engine._ALPHA_SCREENMODE = 10;
  10454. Engine._DELAYLOADSTATE_NONE = 0;
  10455. Engine._DELAYLOADSTATE_LOADED = 1;
  10456. Engine._DELAYLOADSTATE_LOADING = 2;
  10457. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  10458. Engine._TEXTUREFORMAT_ALPHA = 0;
  10459. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  10460. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  10461. Engine._TEXTUREFORMAT_RGB = 4;
  10462. Engine._TEXTUREFORMAT_RGBA = 5;
  10463. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  10464. Engine._TEXTURETYPE_FLOAT = 1;
  10465. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  10466. // Depht or Stencil test Constants.
  10467. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  10468. 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.
  10469. 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.
  10470. 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.
  10471. 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.
  10472. 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.
  10473. 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.
  10474. 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.
  10475. Engine.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10476. Engine.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10477. Engine.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10478. // Stencil Actions Constants.
  10479. Engine._KEEP = 0x1E00;
  10480. Engine._REPLACE = 0x1E01;
  10481. Engine._INCR = 0x1E02;
  10482. Engine._DECR = 0x1E03;
  10483. Engine._INVERT = 0x150A;
  10484. Engine._INCR_WRAP = 0x8507;
  10485. Engine._DECR_WRAP = 0x8508;
  10486. // Texture rescaling mode
  10487. Engine._SCALEMODE_FLOOR = 1;
  10488. Engine._SCALEMODE_NEAREST = 2;
  10489. Engine._SCALEMODE_CEILING = 3;
  10490. // Updatable statics so stick with vars here
  10491. Engine.CollisionsEpsilon = 0.001;
  10492. Engine.CodeRepository = "src/";
  10493. Engine.ShadersRepository = "src/Shaders/";
  10494. BABYLON.Engine = Engine;
  10495. })(BABYLON || (BABYLON = {}));
  10496. //# sourceMappingURL=babylon.engine.js.map
  10497. /// <reference path="Tools\babylon.decorators.ts" />
  10498. var BABYLON;
  10499. (function (BABYLON) {
  10500. /**
  10501. * Node is the basic class for all scene objects (Mesh, Light Camera).
  10502. */
  10503. var Node = (function () {
  10504. /**
  10505. * @constructor
  10506. * @param {string} name - the name and id to be given to this node
  10507. * @param {BABYLON.Scene} the scene this node will be added to
  10508. */
  10509. function Node(name, scene) {
  10510. this.state = "";
  10511. this.metadata = null;
  10512. this.doNotSerialize = false;
  10513. this.animations = new Array();
  10514. this._ranges = {};
  10515. this._childrenFlag = -1;
  10516. this._isEnabled = true;
  10517. this._isReady = true;
  10518. this._currentRenderId = -1;
  10519. this._parentRenderId = -1;
  10520. /**
  10521. * An event triggered when the mesh is disposed.
  10522. * @type {BABYLON.Observable}
  10523. */
  10524. this.onDisposeObservable = new BABYLON.Observable();
  10525. this.name = name;
  10526. this.id = name;
  10527. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  10528. this._initCache();
  10529. }
  10530. Object.defineProperty(Node.prototype, "parent", {
  10531. get: function () {
  10532. return this._parentNode;
  10533. },
  10534. set: function (parent) {
  10535. if (this._parentNode === parent) {
  10536. return;
  10537. }
  10538. if (this._parentNode) {
  10539. var index = this._parentNode._children.indexOf(this);
  10540. if (index !== -1) {
  10541. this._parentNode._children.splice(index, 1);
  10542. }
  10543. }
  10544. this._parentNode = parent;
  10545. if (this._parentNode) {
  10546. if (!this._parentNode._children) {
  10547. this._parentNode._children = new Array();
  10548. }
  10549. this._parentNode._children.push(this);
  10550. }
  10551. },
  10552. enumerable: true,
  10553. configurable: true
  10554. });
  10555. Node.prototype.getClassName = function () {
  10556. return "Node";
  10557. };
  10558. Object.defineProperty(Node.prototype, "onDispose", {
  10559. set: function (callback) {
  10560. if (this._onDisposeObserver) {
  10561. this.onDisposeObservable.remove(this._onDisposeObserver);
  10562. }
  10563. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10564. },
  10565. enumerable: true,
  10566. configurable: true
  10567. });
  10568. Node.prototype.getScene = function () {
  10569. return this._scene;
  10570. };
  10571. Node.prototype.getEngine = function () {
  10572. return this._scene.getEngine();
  10573. };
  10574. // override it in derived class
  10575. Node.prototype.getWorldMatrix = function () {
  10576. return BABYLON.Matrix.Identity();
  10577. };
  10578. // override it in derived class if you add new variables to the cache
  10579. // and call the parent class method
  10580. Node.prototype._initCache = function () {
  10581. this._cache = {};
  10582. this._cache.parent = undefined;
  10583. };
  10584. Node.prototype.updateCache = function (force) {
  10585. if (!force && this.isSynchronized())
  10586. return;
  10587. this._cache.parent = this.parent;
  10588. this._updateCache();
  10589. };
  10590. // override it in derived class if you add new variables to the cache
  10591. // and call the parent class method if !ignoreParentClass
  10592. Node.prototype._updateCache = function (ignoreParentClass) {
  10593. };
  10594. // override it in derived class if you add new variables to the cache
  10595. Node.prototype._isSynchronized = function () {
  10596. return true;
  10597. };
  10598. Node.prototype._markSyncedWithParent = function () {
  10599. this._parentRenderId = this.parent._currentRenderId;
  10600. };
  10601. Node.prototype.isSynchronizedWithParent = function () {
  10602. if (!this.parent) {
  10603. return true;
  10604. }
  10605. if (this._parentRenderId !== this.parent._currentRenderId) {
  10606. return false;
  10607. }
  10608. return this.parent.isSynchronized();
  10609. };
  10610. Node.prototype.isSynchronized = function (updateCache) {
  10611. var check = this.hasNewParent();
  10612. check = check || !this.isSynchronizedWithParent();
  10613. check = check || !this._isSynchronized();
  10614. if (updateCache)
  10615. this.updateCache(true);
  10616. return !check;
  10617. };
  10618. Node.prototype.hasNewParent = function (update) {
  10619. if (this._cache.parent === this.parent)
  10620. return false;
  10621. if (update)
  10622. this._cache.parent = this.parent;
  10623. return true;
  10624. };
  10625. /**
  10626. * Is this node ready to be used/rendered
  10627. * @return {boolean} is it ready
  10628. */
  10629. Node.prototype.isReady = function () {
  10630. return this._isReady;
  10631. };
  10632. /**
  10633. * Is this node enabled.
  10634. * If the node has a parent and is enabled, the parent will be inspected as well.
  10635. * @return {boolean} whether this node (and its parent) is enabled.
  10636. * @see setEnabled
  10637. */
  10638. Node.prototype.isEnabled = function () {
  10639. if (!this._isEnabled) {
  10640. return false;
  10641. }
  10642. if (this.parent) {
  10643. return this.parent.isEnabled();
  10644. }
  10645. return true;
  10646. };
  10647. /**
  10648. * Set the enabled state of this node.
  10649. * @param {boolean} value - the new enabled state
  10650. * @see isEnabled
  10651. */
  10652. Node.prototype.setEnabled = function (value) {
  10653. this._isEnabled = value;
  10654. };
  10655. /**
  10656. * Is this node a descendant of the given node.
  10657. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  10658. * @param {BABYLON.Node} ancestor - The parent node to inspect
  10659. * @see parent
  10660. */
  10661. Node.prototype.isDescendantOf = function (ancestor) {
  10662. if (this.parent) {
  10663. if (this.parent === ancestor) {
  10664. return true;
  10665. }
  10666. return this.parent.isDescendantOf(ancestor);
  10667. }
  10668. return false;
  10669. };
  10670. /**
  10671. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  10672. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  10673. * @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.
  10674. * @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.
  10675. */
  10676. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  10677. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  10678. if (!this._children) {
  10679. return;
  10680. }
  10681. for (var index = 0; index < this._children.length; index++) {
  10682. var item = this._children[index];
  10683. if (!predicate || predicate(item)) {
  10684. results.push(item);
  10685. }
  10686. if (!directDescendantsOnly) {
  10687. item._getDescendants(results, false, predicate);
  10688. }
  10689. }
  10690. };
  10691. /**
  10692. * Will return all nodes that have this node as ascendant.
  10693. * @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.
  10694. * @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.
  10695. * @return {BABYLON.Node[]} all children nodes of all types.
  10696. */
  10697. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  10698. var results = [];
  10699. this._getDescendants(results, directDescendantsOnly, predicate);
  10700. return results;
  10701. };
  10702. /**
  10703. * Get all child-meshes of this node.
  10704. */
  10705. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  10706. var results = [];
  10707. this._getDescendants(results, directDecendantsOnly, function (node) {
  10708. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  10709. });
  10710. return results;
  10711. };
  10712. /**
  10713. * Get all direct children of this node.
  10714. */
  10715. Node.prototype.getChildren = function (predicate) {
  10716. return this.getDescendants(true, predicate);
  10717. };
  10718. Node.prototype._setReady = function (state) {
  10719. if (state === this._isReady) {
  10720. return;
  10721. }
  10722. if (!state) {
  10723. this._isReady = false;
  10724. return;
  10725. }
  10726. this._isReady = true;
  10727. if (this.onReady) {
  10728. this.onReady(this);
  10729. }
  10730. };
  10731. Node.prototype.getAnimationByName = function (name) {
  10732. for (var i = 0; i < this.animations.length; i++) {
  10733. var animation = this.animations[i];
  10734. if (animation.name === name) {
  10735. return animation;
  10736. }
  10737. }
  10738. return null;
  10739. };
  10740. Node.prototype.createAnimationRange = function (name, from, to) {
  10741. // check name not already in use
  10742. if (!this._ranges[name]) {
  10743. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  10744. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10745. if (this.animations[i]) {
  10746. this.animations[i].createRange(name, from, to);
  10747. }
  10748. }
  10749. }
  10750. };
  10751. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  10752. if (deleteFrames === void 0) { deleteFrames = true; }
  10753. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10754. if (this.animations[i]) {
  10755. this.animations[i].deleteRange(name, deleteFrames);
  10756. }
  10757. }
  10758. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  10759. };
  10760. Node.prototype.getAnimationRange = function (name) {
  10761. return this._ranges[name];
  10762. };
  10763. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  10764. var range = this.getAnimationRange(name);
  10765. if (!range) {
  10766. return null;
  10767. }
  10768. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  10769. };
  10770. Node.prototype.serializeAnimationRanges = function () {
  10771. var serializationRanges = [];
  10772. for (var name in this._ranges) {
  10773. var range = {};
  10774. range.name = name;
  10775. range.from = this._ranges[name].from;
  10776. range.to = this._ranges[name].to;
  10777. serializationRanges.push(range);
  10778. }
  10779. return serializationRanges;
  10780. };
  10781. Node.prototype.dispose = function () {
  10782. this.parent = null;
  10783. // Callback
  10784. this.onDisposeObservable.notifyObservers(this);
  10785. this.onDisposeObservable.clear();
  10786. };
  10787. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  10788. if (parsedNode.ranges) {
  10789. for (var index = 0; index < parsedNode.ranges.length; index++) {
  10790. var data = parsedNode.ranges[index];
  10791. node.createAnimationRange(data.name, data.from, data.to);
  10792. }
  10793. }
  10794. };
  10795. return Node;
  10796. }());
  10797. __decorate([
  10798. BABYLON.serialize()
  10799. ], Node.prototype, "name", void 0);
  10800. __decorate([
  10801. BABYLON.serialize()
  10802. ], Node.prototype, "id", void 0);
  10803. __decorate([
  10804. BABYLON.serialize()
  10805. ], Node.prototype, "uniqueId", void 0);
  10806. __decorate([
  10807. BABYLON.serialize()
  10808. ], Node.prototype, "state", void 0);
  10809. __decorate([
  10810. BABYLON.serialize()
  10811. ], Node.prototype, "metadata", void 0);
  10812. BABYLON.Node = Node;
  10813. })(BABYLON || (BABYLON = {}));
  10814. //# sourceMappingURL=babylon.node.js.map
  10815. var BABYLON;
  10816. (function (BABYLON) {
  10817. var BoundingSphere = (function () {
  10818. function BoundingSphere(minimum, maximum) {
  10819. this.minimum = minimum;
  10820. this.maximum = maximum;
  10821. this._tempRadiusVector = BABYLON.Vector3.Zero();
  10822. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  10823. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  10824. this.radius = distance * 0.5;
  10825. this.centerWorld = BABYLON.Vector3.Zero();
  10826. this._update(BABYLON.Matrix.Identity());
  10827. }
  10828. // Methods
  10829. BoundingSphere.prototype._update = function (world) {
  10830. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  10831. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  10832. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  10833. };
  10834. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  10835. for (var i = 0; i < 6; i++) {
  10836. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  10837. return false;
  10838. }
  10839. return true;
  10840. };
  10841. BoundingSphere.prototype.intersectsPoint = function (point) {
  10842. var x = this.centerWorld.x - point.x;
  10843. var y = this.centerWorld.y - point.y;
  10844. var z = this.centerWorld.z - point.z;
  10845. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10846. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  10847. return false;
  10848. return true;
  10849. };
  10850. // Statics
  10851. BoundingSphere.Intersects = function (sphere0, sphere1) {
  10852. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  10853. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  10854. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  10855. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10856. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  10857. return false;
  10858. return true;
  10859. };
  10860. return BoundingSphere;
  10861. }());
  10862. BABYLON.BoundingSphere = BoundingSphere;
  10863. })(BABYLON || (BABYLON = {}));
  10864. //# sourceMappingURL=babylon.boundingSphere.js.map
  10865. var BABYLON;
  10866. (function (BABYLON) {
  10867. var BoundingBox = (function () {
  10868. function BoundingBox(minimum, maximum) {
  10869. this.minimum = minimum;
  10870. this.maximum = maximum;
  10871. this.vectors = new Array();
  10872. this.vectorsWorld = new Array();
  10873. // Bounding vectors
  10874. this.vectors.push(this.minimum.clone());
  10875. this.vectors.push(this.maximum.clone());
  10876. this.vectors.push(this.minimum.clone());
  10877. this.vectors[2].x = this.maximum.x;
  10878. this.vectors.push(this.minimum.clone());
  10879. this.vectors[3].y = this.maximum.y;
  10880. this.vectors.push(this.minimum.clone());
  10881. this.vectors[4].z = this.maximum.z;
  10882. this.vectors.push(this.maximum.clone());
  10883. this.vectors[5].z = this.minimum.z;
  10884. this.vectors.push(this.maximum.clone());
  10885. this.vectors[6].x = this.minimum.x;
  10886. this.vectors.push(this.maximum.clone());
  10887. this.vectors[7].y = this.minimum.y;
  10888. // OBB
  10889. this.center = this.maximum.add(this.minimum).scale(0.5);
  10890. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  10891. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  10892. // World
  10893. for (var index = 0; index < this.vectors.length; index++) {
  10894. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  10895. }
  10896. this.minimumWorld = BABYLON.Vector3.Zero();
  10897. this.maximumWorld = BABYLON.Vector3.Zero();
  10898. this.centerWorld = BABYLON.Vector3.Zero();
  10899. this.extendSizeWorld = BABYLON.Vector3.Zero();
  10900. this._update(BABYLON.Matrix.Identity());
  10901. }
  10902. // Methods
  10903. BoundingBox.prototype.getWorldMatrix = function () {
  10904. return this._worldMatrix;
  10905. };
  10906. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  10907. this._worldMatrix.copyFrom(matrix);
  10908. return this;
  10909. };
  10910. BoundingBox.prototype._update = function (world) {
  10911. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  10912. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  10913. for (var index = 0; index < this.vectors.length; index++) {
  10914. var v = this.vectorsWorld[index];
  10915. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  10916. if (v.x < this.minimumWorld.x)
  10917. this.minimumWorld.x = v.x;
  10918. if (v.y < this.minimumWorld.y)
  10919. this.minimumWorld.y = v.y;
  10920. if (v.z < this.minimumWorld.z)
  10921. this.minimumWorld.z = v.z;
  10922. if (v.x > this.maximumWorld.x)
  10923. this.maximumWorld.x = v.x;
  10924. if (v.y > this.maximumWorld.y)
  10925. this.maximumWorld.y = v.y;
  10926. if (v.z > this.maximumWorld.z)
  10927. this.maximumWorld.z = v.z;
  10928. }
  10929. // Extend
  10930. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  10931. this.extendSizeWorld.scaleInPlace(0.5);
  10932. // OBB
  10933. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  10934. this.centerWorld.scaleInPlace(0.5);
  10935. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  10936. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  10937. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  10938. this._worldMatrix = world;
  10939. };
  10940. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  10941. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  10942. };
  10943. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10944. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  10945. };
  10946. BoundingBox.prototype.intersectsPoint = function (point) {
  10947. var delta = -BABYLON.Epsilon;
  10948. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  10949. return false;
  10950. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  10951. return false;
  10952. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  10953. return false;
  10954. return true;
  10955. };
  10956. BoundingBox.prototype.intersectsSphere = function (sphere) {
  10957. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  10958. };
  10959. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  10960. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  10961. return false;
  10962. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  10963. return false;
  10964. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  10965. return false;
  10966. return true;
  10967. };
  10968. // Statics
  10969. BoundingBox.Intersects = function (box0, box1) {
  10970. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  10971. return false;
  10972. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  10973. return false;
  10974. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  10975. return false;
  10976. return true;
  10977. };
  10978. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  10979. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  10980. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  10981. return (num <= (sphereRadius * sphereRadius));
  10982. };
  10983. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  10984. for (var p = 0; p < 6; p++) {
  10985. for (var i = 0; i < 8; i++) {
  10986. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  10987. return false;
  10988. }
  10989. }
  10990. }
  10991. return true;
  10992. };
  10993. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  10994. for (var p = 0; p < 6; p++) {
  10995. var inCount = 8;
  10996. for (var i = 0; i < 8; i++) {
  10997. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  10998. --inCount;
  10999. }
  11000. else {
  11001. break;
  11002. }
  11003. }
  11004. if (inCount === 0)
  11005. return false;
  11006. }
  11007. return true;
  11008. };
  11009. return BoundingBox;
  11010. }());
  11011. BABYLON.BoundingBox = BoundingBox;
  11012. })(BABYLON || (BABYLON = {}));
  11013. //# sourceMappingURL=babylon.boundingBox.js.map
  11014. var BABYLON;
  11015. (function (BABYLON) {
  11016. var computeBoxExtents = function (axis, box) {
  11017. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11018. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11019. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11020. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11021. var r = r0 + r1 + r2;
  11022. return {
  11023. min: p - r,
  11024. max: p + r
  11025. };
  11026. };
  11027. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11028. var axisOverlap = function (axis, box0, box1) {
  11029. var result0 = computeBoxExtents(axis, box0);
  11030. var result1 = computeBoxExtents(axis, box1);
  11031. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11032. };
  11033. var BoundingInfo = (function () {
  11034. function BoundingInfo(minimum, maximum) {
  11035. this.minimum = minimum;
  11036. this.maximum = maximum;
  11037. this._isLocked = false;
  11038. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11039. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11040. }
  11041. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11042. get: function () {
  11043. return this._isLocked;
  11044. },
  11045. set: function (value) {
  11046. this._isLocked = value;
  11047. },
  11048. enumerable: true,
  11049. configurable: true
  11050. });
  11051. // Methods
  11052. BoundingInfo.prototype.update = function (world) {
  11053. if (this._isLocked) {
  11054. return;
  11055. }
  11056. this.boundingBox._update(world);
  11057. this.boundingSphere._update(world);
  11058. };
  11059. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11060. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11061. return false;
  11062. return this.boundingBox.isInFrustum(frustumPlanes);
  11063. };
  11064. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11065. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11066. };
  11067. BoundingInfo.prototype._checkCollision = function (collider) {
  11068. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11069. };
  11070. BoundingInfo.prototype.intersectsPoint = function (point) {
  11071. if (!this.boundingSphere.centerWorld) {
  11072. return false;
  11073. }
  11074. if (!this.boundingSphere.intersectsPoint(point)) {
  11075. return false;
  11076. }
  11077. if (!this.boundingBox.intersectsPoint(point)) {
  11078. return false;
  11079. }
  11080. return true;
  11081. };
  11082. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11083. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11084. return false;
  11085. }
  11086. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11087. return false;
  11088. }
  11089. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11090. return false;
  11091. }
  11092. if (!precise) {
  11093. return true;
  11094. }
  11095. var box0 = this.boundingBox;
  11096. var box1 = boundingInfo.boundingBox;
  11097. if (!axisOverlap(box0.directions[0], box0, box1))
  11098. return false;
  11099. if (!axisOverlap(box0.directions[1], box0, box1))
  11100. return false;
  11101. if (!axisOverlap(box0.directions[2], box0, box1))
  11102. return false;
  11103. if (!axisOverlap(box1.directions[0], box0, box1))
  11104. return false;
  11105. if (!axisOverlap(box1.directions[1], box0, box1))
  11106. return false;
  11107. if (!axisOverlap(box1.directions[2], box0, box1))
  11108. return false;
  11109. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11110. return false;
  11111. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11112. return false;
  11113. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11114. return false;
  11115. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11116. return false;
  11117. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11118. return false;
  11119. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11120. return false;
  11121. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11122. return false;
  11123. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11124. return false;
  11125. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11126. return false;
  11127. return true;
  11128. };
  11129. return BoundingInfo;
  11130. }());
  11131. BABYLON.BoundingInfo = BoundingInfo;
  11132. })(BABYLON || (BABYLON = {}));
  11133. //# sourceMappingURL=babylon.boundingInfo.js.map
  11134. var BABYLON;
  11135. (function (BABYLON) {
  11136. var AbstractMesh = (function (_super) {
  11137. __extends(AbstractMesh, _super);
  11138. // Constructor
  11139. function AbstractMesh(name, scene) {
  11140. var _this = _super.call(this, name, scene) || this;
  11141. _this._facetNb = 0; // facet number
  11142. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  11143. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  11144. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  11145. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  11146. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  11147. _this._subDiv = {
  11148. max: 1,
  11149. X: 1,
  11150. Y: 1,
  11151. Z: 1
  11152. };
  11153. // Events
  11154. /**
  11155. * An event triggered when this mesh collides with another one
  11156. * @type {BABYLON.Observable}
  11157. */
  11158. _this.onCollideObservable = new BABYLON.Observable();
  11159. /**
  11160. * An event triggered when the collision's position changes
  11161. * @type {BABYLON.Observable}
  11162. */
  11163. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  11164. /**
  11165. * An event triggered after the world matrix is updated
  11166. * @type {BABYLON.Observable}
  11167. */
  11168. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  11169. // Properties
  11170. _this.definedFacingForward = true; // orientation for POV movement & rotation
  11171. _this.position = BABYLON.Vector3.Zero();
  11172. _this._rotation = BABYLON.Vector3.Zero();
  11173. _this._scaling = BABYLON.Vector3.One();
  11174. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  11175. _this.visibility = 1.0;
  11176. _this.alphaIndex = Number.MAX_VALUE;
  11177. _this.infiniteDistance = false;
  11178. _this.isVisible = true;
  11179. _this.isPickable = true;
  11180. _this.showBoundingBox = false;
  11181. _this.showSubMeshesBoundingBox = false;
  11182. _this.isBlocker = false;
  11183. _this.renderingGroupId = 0;
  11184. _this._receiveShadows = false;
  11185. _this.renderOutline = false;
  11186. _this.outlineColor = BABYLON.Color3.Red();
  11187. _this.outlineWidth = 0.02;
  11188. _this.renderOverlay = false;
  11189. _this.overlayColor = BABYLON.Color3.Red();
  11190. _this.overlayAlpha = 0.5;
  11191. _this._hasVertexAlpha = false;
  11192. _this._useVertexColors = true;
  11193. _this._computeBonesUsingShaders = true;
  11194. _this._numBoneInfluencers = 4;
  11195. _this._applyFog = true;
  11196. _this.scalingDeterminant = 1;
  11197. _this.useOctreeForRenderingSelection = true;
  11198. _this.useOctreeForPicking = true;
  11199. _this.useOctreeForCollisions = true;
  11200. _this.layerMask = 0x0FFFFFFF;
  11201. /**
  11202. * True if the mesh must be rendered in any case.
  11203. */
  11204. _this.alwaysSelectAsActiveMesh = false;
  11205. // Collisions
  11206. _this._checkCollisions = false;
  11207. _this._collisionMask = -1;
  11208. _this._collisionGroup = -1;
  11209. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11210. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  11211. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11212. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11213. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11214. // Edges
  11215. _this.edgesWidth = 1;
  11216. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  11217. // Cache
  11218. _this._localWorld = BABYLON.Matrix.Zero();
  11219. _this._worldMatrix = BABYLON.Matrix.Zero();
  11220. _this._absolutePosition = BABYLON.Vector3.Zero();
  11221. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  11222. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  11223. _this._isDirty = false;
  11224. _this._pivotMatrix = BABYLON.Matrix.Identity();
  11225. _this._isDisposed = false;
  11226. _this._renderId = 0;
  11227. _this._intersectionsInProgress = new Array();
  11228. _this._isWorldMatrixFrozen = false;
  11229. _this._unIndexed = false;
  11230. _this._lightSources = new Array();
  11231. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11232. if (collidedMesh === void 0) { collidedMesh = null; }
  11233. //TODO move this to the collision coordinator!
  11234. if (_this.getScene().workerCollisions)
  11235. newPosition.multiplyInPlace(_this._collider.radius);
  11236. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  11237. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  11238. _this.position.addInPlace(_this._diffPositionForCollisions);
  11239. }
  11240. if (collidedMesh) {
  11241. _this.onCollideObservable.notifyObservers(collidedMesh);
  11242. }
  11243. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  11244. };
  11245. _this.getScene().addMesh(_this);
  11246. _this._resyncLightSources();
  11247. return _this;
  11248. }
  11249. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  11250. get: function () {
  11251. return AbstractMesh._BILLBOARDMODE_NONE;
  11252. },
  11253. enumerable: true,
  11254. configurable: true
  11255. });
  11256. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  11257. get: function () {
  11258. return AbstractMesh._BILLBOARDMODE_X;
  11259. },
  11260. enumerable: true,
  11261. configurable: true
  11262. });
  11263. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  11264. get: function () {
  11265. return AbstractMesh._BILLBOARDMODE_Y;
  11266. },
  11267. enumerable: true,
  11268. configurable: true
  11269. });
  11270. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  11271. get: function () {
  11272. return AbstractMesh._BILLBOARDMODE_Z;
  11273. },
  11274. enumerable: true,
  11275. configurable: true
  11276. });
  11277. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  11278. get: function () {
  11279. return AbstractMesh._BILLBOARDMODE_ALL;
  11280. },
  11281. enumerable: true,
  11282. configurable: true
  11283. });
  11284. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  11285. /**
  11286. * Read-only : the number of facets in the mesh
  11287. */
  11288. get: function () {
  11289. return this._facetNb;
  11290. },
  11291. enumerable: true,
  11292. configurable: true
  11293. });
  11294. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  11295. /**
  11296. * The number (integer) of subdivisions per axis in the partioning space
  11297. */
  11298. get: function () {
  11299. return this._partitioningSubdivisions;
  11300. },
  11301. set: function (nb) {
  11302. this._partitioningSubdivisions = nb;
  11303. },
  11304. enumerable: true,
  11305. configurable: true
  11306. });
  11307. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  11308. /**
  11309. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  11310. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  11311. */
  11312. get: function () {
  11313. return this._partitioningBBoxRatio;
  11314. },
  11315. set: function (ratio) {
  11316. this._partitioningBBoxRatio = ratio;
  11317. },
  11318. enumerable: true,
  11319. configurable: true
  11320. });
  11321. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  11322. /**
  11323. * Read-only boolean : is the feature facetData enabled ?
  11324. */
  11325. get: function () {
  11326. return this._facetDataEnabled;
  11327. },
  11328. enumerable: true,
  11329. configurable: true
  11330. });
  11331. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  11332. set: function (callback) {
  11333. if (this._onCollideObserver) {
  11334. this.onCollideObservable.remove(this._onCollideObserver);
  11335. }
  11336. this._onCollideObserver = this.onCollideObservable.add(callback);
  11337. },
  11338. enumerable: true,
  11339. configurable: true
  11340. });
  11341. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  11342. set: function (callback) {
  11343. if (this._onCollisionPositionChangeObserver) {
  11344. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  11345. }
  11346. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  11347. },
  11348. enumerable: true,
  11349. configurable: true
  11350. });
  11351. Object.defineProperty(AbstractMesh.prototype, "material", {
  11352. get: function () {
  11353. return this._material;
  11354. },
  11355. set: function (value) {
  11356. if (this._material === value) {
  11357. return;
  11358. }
  11359. this._material = value;
  11360. if (!this.subMeshes) {
  11361. return;
  11362. }
  11363. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11364. var subMesh = _a[_i];
  11365. subMesh.setEffect(null);
  11366. }
  11367. },
  11368. enumerable: true,
  11369. configurable: true
  11370. });
  11371. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  11372. get: function () {
  11373. return this._receiveShadows;
  11374. },
  11375. set: function (value) {
  11376. if (this._receiveShadows === value) {
  11377. return;
  11378. }
  11379. this._receiveShadows = value;
  11380. this._markSubMeshesAsLightDirty();
  11381. },
  11382. enumerable: true,
  11383. configurable: true
  11384. });
  11385. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  11386. get: function () {
  11387. return this._hasVertexAlpha;
  11388. },
  11389. set: function (value) {
  11390. if (this._hasVertexAlpha === value) {
  11391. return;
  11392. }
  11393. this._hasVertexAlpha = value;
  11394. this._markSubMeshesAsAttributesDirty();
  11395. },
  11396. enumerable: true,
  11397. configurable: true
  11398. });
  11399. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  11400. get: function () {
  11401. return this._useVertexColors;
  11402. },
  11403. set: function (value) {
  11404. if (this._useVertexColors === value) {
  11405. return;
  11406. }
  11407. this._useVertexColors = value;
  11408. this._markSubMeshesAsAttributesDirty();
  11409. },
  11410. enumerable: true,
  11411. configurable: true
  11412. });
  11413. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  11414. get: function () {
  11415. return this._computeBonesUsingShaders;
  11416. },
  11417. set: function (value) {
  11418. if (this._computeBonesUsingShaders === value) {
  11419. return;
  11420. }
  11421. this._computeBonesUsingShaders = value;
  11422. this._markSubMeshesAsAttributesDirty();
  11423. },
  11424. enumerable: true,
  11425. configurable: true
  11426. });
  11427. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  11428. get: function () {
  11429. return this._numBoneInfluencers;
  11430. },
  11431. set: function (value) {
  11432. if (this._numBoneInfluencers === value) {
  11433. return;
  11434. }
  11435. this._numBoneInfluencers = value;
  11436. this._markSubMeshesAsAttributesDirty();
  11437. },
  11438. enumerable: true,
  11439. configurable: true
  11440. });
  11441. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  11442. get: function () {
  11443. return this._applyFog;
  11444. },
  11445. set: function (value) {
  11446. if (this._applyFog === value) {
  11447. return;
  11448. }
  11449. this._applyFog = value;
  11450. this._markSubMeshesAsMiscDirty();
  11451. },
  11452. enumerable: true,
  11453. configurable: true
  11454. });
  11455. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  11456. get: function () {
  11457. return this._collisionMask;
  11458. },
  11459. set: function (mask) {
  11460. this._collisionMask = !isNaN(mask) ? mask : -1;
  11461. },
  11462. enumerable: true,
  11463. configurable: true
  11464. });
  11465. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  11466. get: function () {
  11467. return this._collisionGroup;
  11468. },
  11469. set: function (mask) {
  11470. this._collisionGroup = !isNaN(mask) ? mask : -1;
  11471. },
  11472. enumerable: true,
  11473. configurable: true
  11474. });
  11475. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  11476. get: function () {
  11477. return null;
  11478. },
  11479. enumerable: true,
  11480. configurable: true
  11481. });
  11482. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  11483. get: function () {
  11484. return this._skeleton;
  11485. },
  11486. set: function (value) {
  11487. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  11488. this._skeleton._unregisterMeshWithPoseMatrix(this);
  11489. }
  11490. if (value && value.needInitialSkinMatrix) {
  11491. value._registerMeshWithPoseMatrix(this);
  11492. }
  11493. this._skeleton = value;
  11494. if (!this._skeleton) {
  11495. this._bonesTransformMatrices = null;
  11496. }
  11497. this._markSubMeshesAsAttributesDirty();
  11498. },
  11499. enumerable: true,
  11500. configurable: true
  11501. });
  11502. /**
  11503. * Returns the string "AbstractMesh"
  11504. */
  11505. AbstractMesh.prototype.getClassName = function () {
  11506. return "AbstractMesh";
  11507. };
  11508. /**
  11509. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11510. */
  11511. AbstractMesh.prototype.toString = function (fullDetails) {
  11512. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  11513. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  11514. if (this._skeleton) {
  11515. ret += ", skeleton: " + this._skeleton.name;
  11516. }
  11517. if (fullDetails) {
  11518. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  11519. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  11520. }
  11521. return ret;
  11522. };
  11523. AbstractMesh.prototype._resyncLightSources = function () {
  11524. this._lightSources.length = 0;
  11525. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  11526. var light = _a[_i];
  11527. if (!light.isEnabled()) {
  11528. continue;
  11529. }
  11530. if (light.canAffectMesh(this)) {
  11531. this._lightSources.push(light);
  11532. }
  11533. }
  11534. this._markSubMeshesAsLightDirty();
  11535. };
  11536. AbstractMesh.prototype._resyncLighSource = function (light) {
  11537. var isIn = light.isEnabled() && light.canAffectMesh(this);
  11538. var index = this._lightSources.indexOf(light);
  11539. if (index === -1) {
  11540. if (!isIn) {
  11541. return;
  11542. }
  11543. this._lightSources.push(light);
  11544. }
  11545. else {
  11546. if (isIn) {
  11547. return;
  11548. }
  11549. this._lightSources.splice(index, 1);
  11550. }
  11551. this._markSubMeshesAsLightDirty();
  11552. };
  11553. AbstractMesh.prototype._removeLightSource = function (light) {
  11554. var index = this._lightSources.indexOf(light);
  11555. if (index === -1) {
  11556. return;
  11557. }
  11558. this._lightSources.splice(index, 1);
  11559. };
  11560. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  11561. if (!this.subMeshes) {
  11562. return;
  11563. }
  11564. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11565. var subMesh = _a[_i];
  11566. if (subMesh._materialDefines) {
  11567. func(subMesh._materialDefines);
  11568. }
  11569. }
  11570. };
  11571. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  11572. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  11573. };
  11574. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  11575. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  11576. };
  11577. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  11578. if (!this.subMeshes) {
  11579. return;
  11580. }
  11581. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11582. var subMesh = _a[_i];
  11583. var material = subMesh.getMaterial();
  11584. if (material) {
  11585. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  11586. }
  11587. }
  11588. };
  11589. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  11590. /**
  11591. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  11592. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  11593. * Default : (0.0, 0.0, 0.0)
  11594. */
  11595. get: function () {
  11596. return this._rotation;
  11597. },
  11598. set: function (newRotation) {
  11599. this._rotation = newRotation;
  11600. },
  11601. enumerable: true,
  11602. configurable: true
  11603. });
  11604. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  11605. /**
  11606. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  11607. * Default : (1.0, 1.0, 1.0)
  11608. */
  11609. get: function () {
  11610. return this._scaling;
  11611. },
  11612. set: function (newScaling) {
  11613. this._scaling = newScaling;
  11614. if (this.physicsImpostor) {
  11615. this.physicsImpostor.forceUpdate();
  11616. }
  11617. },
  11618. enumerable: true,
  11619. configurable: true
  11620. });
  11621. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  11622. /**
  11623. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  11624. * It's null by default.
  11625. * 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)
  11626. */
  11627. get: function () {
  11628. return this._rotationQuaternion;
  11629. },
  11630. set: function (quaternion) {
  11631. this._rotationQuaternion = quaternion;
  11632. //reset the rotation vector.
  11633. if (quaternion && this.rotation.length()) {
  11634. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  11635. }
  11636. },
  11637. enumerable: true,
  11638. configurable: true
  11639. });
  11640. // Methods
  11641. /**
  11642. * Copies the paramater passed Matrix into the mesh Pose matrix.
  11643. * Returns the AbstractMesh.
  11644. */
  11645. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  11646. this._poseMatrix.copyFrom(matrix);
  11647. return this;
  11648. };
  11649. /**
  11650. * Returns the mesh Pose matrix.
  11651. * Returned object : Matrix
  11652. */
  11653. AbstractMesh.prototype.getPoseMatrix = function () {
  11654. return this._poseMatrix;
  11655. };
  11656. /**
  11657. * Disables the mesh edger rendering mode.
  11658. * Returns the AbstractMesh.
  11659. */
  11660. AbstractMesh.prototype.disableEdgesRendering = function () {
  11661. if (this._edgesRenderer !== undefined) {
  11662. this._edgesRenderer.dispose();
  11663. this._edgesRenderer = undefined;
  11664. }
  11665. return this;
  11666. };
  11667. /**
  11668. * Enables the edge rendering mode on the mesh.
  11669. * This mode makes the mesh edges visible.
  11670. * Returns the AbstractMesh.
  11671. */
  11672. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  11673. if (epsilon === void 0) { epsilon = 0.95; }
  11674. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  11675. this.disableEdgesRendering();
  11676. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  11677. return this;
  11678. };
  11679. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  11680. /**
  11681. * Returns true if the mesh is blocked. Used by the class Mesh.
  11682. * Returns the boolean `false` by default.
  11683. */
  11684. get: function () {
  11685. return false;
  11686. },
  11687. enumerable: true,
  11688. configurable: true
  11689. });
  11690. /**
  11691. * Returns the mesh itself by default, used by the class Mesh.
  11692. * Returned type : AbstractMesh
  11693. */
  11694. AbstractMesh.prototype.getLOD = function (camera) {
  11695. return this;
  11696. };
  11697. /**
  11698. * Returns 0 by default, used by the class Mesh.
  11699. * Returns an integer.
  11700. */
  11701. AbstractMesh.prototype.getTotalVertices = function () {
  11702. return 0;
  11703. };
  11704. /**
  11705. * Returns null by default, used by the class Mesh.
  11706. * Returned type : integer array
  11707. */
  11708. AbstractMesh.prototype.getIndices = function () {
  11709. return null;
  11710. };
  11711. /**
  11712. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  11713. * Returned type : float array or Float32Array
  11714. */
  11715. AbstractMesh.prototype.getVerticesData = function (kind) {
  11716. return null;
  11717. };
  11718. /**
  11719. * Sets the vertex data of the mesh geometry for the requested `kind`.
  11720. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  11721. * The `data` are either a numeric array either a Float32Array.
  11722. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  11723. * 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).
  11724. * Note that a new underlying VertexBuffer object is created each call.
  11725. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  11726. *
  11727. * Possible `kind` values :
  11728. * - BABYLON.VertexBuffer.PositionKind
  11729. * - BABYLON.VertexBuffer.UVKind
  11730. * - BABYLON.VertexBuffer.UV2Kind
  11731. * - BABYLON.VertexBuffer.UV3Kind
  11732. * - BABYLON.VertexBuffer.UV4Kind
  11733. * - BABYLON.VertexBuffer.UV5Kind
  11734. * - BABYLON.VertexBuffer.UV6Kind
  11735. * - BABYLON.VertexBuffer.ColorKind
  11736. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11737. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11738. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11739. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11740. *
  11741. * Returns the Mesh.
  11742. */
  11743. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  11744. return null;
  11745. };
  11746. /**
  11747. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  11748. * If the mesh has no geometry, it is simply returned as it is.
  11749. * The `data` are either a numeric array either a Float32Array.
  11750. * No new underlying VertexBuffer object is created.
  11751. * 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.
  11752. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  11753. *
  11754. * Possible `kind` values :
  11755. * - BABYLON.VertexBuffer.PositionKind
  11756. * - BABYLON.VertexBuffer.UVKind
  11757. * - BABYLON.VertexBuffer.UV2Kind
  11758. * - BABYLON.VertexBuffer.UV3Kind
  11759. * - BABYLON.VertexBuffer.UV4Kind
  11760. * - BABYLON.VertexBuffer.UV5Kind
  11761. * - BABYLON.VertexBuffer.UV6Kind
  11762. * - BABYLON.VertexBuffer.ColorKind
  11763. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11764. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11765. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11766. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11767. *
  11768. * Returns the Mesh.
  11769. */
  11770. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  11771. return null;
  11772. };
  11773. /**
  11774. * Sets the mesh indices.
  11775. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  11776. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  11777. * This method creates a new index buffer each call.
  11778. * Returns the Mesh.
  11779. */
  11780. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  11781. return null;
  11782. };
  11783. /** Returns false by default, used by the class Mesh.
  11784. * Returns a boolean
  11785. */
  11786. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  11787. return false;
  11788. };
  11789. /**
  11790. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  11791. * Returns a BoundingInfo
  11792. */
  11793. AbstractMesh.prototype.getBoundingInfo = function () {
  11794. if (this._masterMesh) {
  11795. return this._masterMesh.getBoundingInfo();
  11796. }
  11797. if (!this._boundingInfo) {
  11798. this._updateBoundingInfo();
  11799. }
  11800. return this._boundingInfo;
  11801. };
  11802. /**
  11803. * Sets a mesh new object BoundingInfo.
  11804. * Returns the AbstractMesh.
  11805. */
  11806. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  11807. this._boundingInfo = boundingInfo;
  11808. return this;
  11809. };
  11810. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  11811. get: function () {
  11812. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  11813. },
  11814. enumerable: true,
  11815. configurable: true
  11816. });
  11817. AbstractMesh.prototype._preActivate = function () {
  11818. };
  11819. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  11820. };
  11821. AbstractMesh.prototype._activate = function (renderId) {
  11822. this._renderId = renderId;
  11823. };
  11824. /**
  11825. * Returns the last update of the World matrix
  11826. * Returns a Matrix.
  11827. */
  11828. AbstractMesh.prototype.getWorldMatrix = function () {
  11829. if (this._masterMesh) {
  11830. return this._masterMesh.getWorldMatrix();
  11831. }
  11832. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  11833. this.computeWorldMatrix();
  11834. }
  11835. return this._worldMatrix;
  11836. };
  11837. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  11838. /**
  11839. * Returns directly the last state of the mesh World matrix.
  11840. * A Matrix is returned.
  11841. */
  11842. get: function () {
  11843. return this._worldMatrix;
  11844. },
  11845. enumerable: true,
  11846. configurable: true
  11847. });
  11848. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  11849. /**
  11850. * Returns the current mesh absolute position.
  11851. * Retuns a Vector3.
  11852. */
  11853. get: function () {
  11854. return this._absolutePosition;
  11855. },
  11856. enumerable: true,
  11857. configurable: true
  11858. });
  11859. /**
  11860. * Prevents the World matrix to be computed any longer.
  11861. * Returns the AbstractMesh.
  11862. */
  11863. AbstractMesh.prototype.freezeWorldMatrix = function () {
  11864. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  11865. this.computeWorldMatrix(true);
  11866. this._isWorldMatrixFrozen = true;
  11867. return this;
  11868. };
  11869. /**
  11870. * Allows back the World matrix computation.
  11871. * Returns the AbstractMesh.
  11872. */
  11873. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  11874. this._isWorldMatrixFrozen = false;
  11875. this.computeWorldMatrix(true);
  11876. return this;
  11877. };
  11878. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  11879. /**
  11880. * True if the World matrix has been frozen.
  11881. * Returns a boolean.
  11882. */
  11883. get: function () {
  11884. return this._isWorldMatrixFrozen;
  11885. },
  11886. enumerable: true,
  11887. configurable: true
  11888. });
  11889. /**
  11890. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  11891. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11892. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  11893. * The passed axis is also normalized.
  11894. * Returns the AbstractMesh.
  11895. */
  11896. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  11897. axis.normalize();
  11898. if (!this.rotationQuaternion) {
  11899. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11900. this.rotation = BABYLON.Vector3.Zero();
  11901. }
  11902. var rotationQuaternion;
  11903. if (!space || space === BABYLON.Space.LOCAL) {
  11904. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11905. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  11906. }
  11907. else {
  11908. if (this.parent) {
  11909. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11910. invertParentWorldMatrix.invert();
  11911. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  11912. }
  11913. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11914. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  11915. }
  11916. return this;
  11917. };
  11918. /**
  11919. * Translates the mesh along the axis vector for the passed distance in the given space.
  11920. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11921. * Returns the AbstractMesh.
  11922. */
  11923. AbstractMesh.prototype.translate = function (axis, distance, space) {
  11924. var displacementVector = axis.scale(distance);
  11925. if (!space || space === BABYLON.Space.LOCAL) {
  11926. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  11927. this.setPositionWithLocalVector(tempV3);
  11928. }
  11929. else {
  11930. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  11931. }
  11932. return this;
  11933. };
  11934. /**
  11935. * Adds a rotation step to the mesh current rotation.
  11936. * x, y, z are Euler angles expressed in radians.
  11937. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  11938. * This means this rotation is made in the mesh local space only.
  11939. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  11940. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  11941. * ```javascript
  11942. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  11943. * ```
  11944. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  11945. * 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.
  11946. * Returns the AbstractMesh.
  11947. */
  11948. AbstractMesh.prototype.addRotation = function (x, y, z) {
  11949. var rotationQuaternion;
  11950. if (this.rotationQuaternion) {
  11951. rotationQuaternion = this.rotationQuaternion;
  11952. }
  11953. else {
  11954. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  11955. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  11956. }
  11957. var accumulation = BABYLON.Tmp.Quaternion[0];
  11958. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  11959. rotationQuaternion.multiplyInPlace(accumulation);
  11960. if (!this.rotationQuaternion) {
  11961. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  11962. }
  11963. return this;
  11964. };
  11965. /**
  11966. * Retuns the mesh absolute position in the World.
  11967. * Returns a Vector3.
  11968. */
  11969. AbstractMesh.prototype.getAbsolutePosition = function () {
  11970. this.computeWorldMatrix();
  11971. return this._absolutePosition;
  11972. };
  11973. /**
  11974. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  11975. * Returns the AbstractMesh.
  11976. */
  11977. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  11978. if (!absolutePosition) {
  11979. return;
  11980. }
  11981. var absolutePositionX;
  11982. var absolutePositionY;
  11983. var absolutePositionZ;
  11984. if (absolutePosition.x === undefined) {
  11985. if (arguments.length < 3) {
  11986. return;
  11987. }
  11988. absolutePositionX = arguments[0];
  11989. absolutePositionY = arguments[1];
  11990. absolutePositionZ = arguments[2];
  11991. }
  11992. else {
  11993. absolutePositionX = absolutePosition.x;
  11994. absolutePositionY = absolutePosition.y;
  11995. absolutePositionZ = absolutePosition.z;
  11996. }
  11997. if (this.parent) {
  11998. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11999. invertParentWorldMatrix.invert();
  12000. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  12001. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  12002. }
  12003. else {
  12004. this.position.x = absolutePositionX;
  12005. this.position.y = absolutePositionY;
  12006. this.position.z = absolutePositionZ;
  12007. }
  12008. return this;
  12009. };
  12010. // ================================== Point of View Movement =================================
  12011. /**
  12012. * Perform relative position change from the point of view of behind the front of the mesh.
  12013. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12014. * Supports definition of mesh facing forward or backward.
  12015. * @param {number} amountRight
  12016. * @param {number} amountUp
  12017. * @param {number} amountForward
  12018. *
  12019. * Returns the AbstractMesh.
  12020. */
  12021. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  12022. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  12023. return this;
  12024. };
  12025. /**
  12026. * Calculate relative position change from the point of view of behind the front of the mesh.
  12027. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12028. * Supports definition of mesh facing forward or backward.
  12029. * @param {number} amountRight
  12030. * @param {number} amountUp
  12031. * @param {number} amountForward
  12032. *
  12033. * Returns a new Vector3.
  12034. */
  12035. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  12036. var rotMatrix = new BABYLON.Matrix();
  12037. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12038. rotQuaternion.toRotationMatrix(rotMatrix);
  12039. var translationDelta = BABYLON.Vector3.Zero();
  12040. var defForwardMult = this.definedFacingForward ? -1 : 1;
  12041. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  12042. return translationDelta;
  12043. };
  12044. // ================================== Point of View Rotation =================================
  12045. /**
  12046. * Perform relative rotation change from the point of view of behind the front of the mesh.
  12047. * Supports definition of mesh facing forward or backward.
  12048. * @param {number} flipBack
  12049. * @param {number} twirlClockwise
  12050. * @param {number} tiltRight
  12051. *
  12052. * Returns the AbstractMesh.
  12053. */
  12054. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12055. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  12056. return this;
  12057. };
  12058. /**
  12059. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  12060. * Supports definition of mesh facing forward or backward.
  12061. * @param {number} flipBack
  12062. * @param {number} twirlClockwise
  12063. * @param {number} tiltRight
  12064. *
  12065. * Returns a new Vector3.
  12066. */
  12067. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12068. var defForwardMult = this.definedFacingForward ? 1 : -1;
  12069. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  12070. };
  12071. /**
  12072. * Sets a new pivot matrix to the mesh.
  12073. * Returns the AbstractMesh.
  12074. */
  12075. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  12076. this._pivotMatrix = matrix;
  12077. this._cache.pivotMatrixUpdated = true;
  12078. return this;
  12079. };
  12080. /**
  12081. * Returns the mesh pivot matrix.
  12082. * Default : Identity.
  12083. * A Matrix is returned.
  12084. */
  12085. AbstractMesh.prototype.getPivotMatrix = function () {
  12086. return this._pivotMatrix;
  12087. };
  12088. AbstractMesh.prototype._isSynchronized = function () {
  12089. if (this._isDirty) {
  12090. return false;
  12091. }
  12092. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12093. return false;
  12094. if (this._cache.pivotMatrixUpdated) {
  12095. return false;
  12096. }
  12097. if (this.infiniteDistance) {
  12098. return false;
  12099. }
  12100. if (!this._cache.position.equals(this.position))
  12101. return false;
  12102. if (this.rotationQuaternion) {
  12103. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12104. return false;
  12105. }
  12106. if (!this._cache.rotation.equals(this.rotation))
  12107. return false;
  12108. if (!this._cache.scaling.equals(this.scaling))
  12109. return false;
  12110. return true;
  12111. };
  12112. AbstractMesh.prototype._initCache = function () {
  12113. _super.prototype._initCache.call(this);
  12114. this._cache.localMatrixUpdated = false;
  12115. this._cache.position = BABYLON.Vector3.Zero();
  12116. this._cache.scaling = BABYLON.Vector3.Zero();
  12117. this._cache.rotation = BABYLON.Vector3.Zero();
  12118. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12119. this._cache.billboardMode = -1;
  12120. };
  12121. AbstractMesh.prototype.markAsDirty = function (property) {
  12122. if (property === "rotation") {
  12123. this.rotationQuaternion = null;
  12124. }
  12125. this._currentRenderId = Number.MAX_VALUE;
  12126. this._isDirty = true;
  12127. return this;
  12128. };
  12129. /**
  12130. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12131. * Returns the AbstractMesh.
  12132. */
  12133. AbstractMesh.prototype._updateBoundingInfo = function () {
  12134. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12135. this._boundingInfo.update(this.worldMatrixFromCache);
  12136. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12137. return this;
  12138. };
  12139. /**
  12140. * Update a mesh's children BoundingInfo objects only.
  12141. * Returns the AbstractMesh.
  12142. */
  12143. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  12144. if (!this.subMeshes) {
  12145. return;
  12146. }
  12147. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  12148. var subMesh = this.subMeshes[subIndex];
  12149. if (!subMesh.IsGlobal) {
  12150. subMesh.updateBoundingInfo(matrix);
  12151. }
  12152. }
  12153. return this;
  12154. };
  12155. /**
  12156. * Computes the mesh World matrix and returns it.
  12157. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  12158. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  12159. * If the parameter `force`is set to `true`, the actual computation is done.
  12160. * Returns the mesh World Matrix.
  12161. */
  12162. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  12163. if (this._isWorldMatrixFrozen) {
  12164. return this._worldMatrix;
  12165. }
  12166. if (!force && this.isSynchronized(true)) {
  12167. this._currentRenderId = this.getScene().getRenderId();
  12168. return this._worldMatrix;
  12169. }
  12170. this._cache.position.copyFrom(this.position);
  12171. this._cache.scaling.copyFrom(this.scaling);
  12172. this._cache.pivotMatrixUpdated = false;
  12173. this._cache.billboardMode = this.billboardMode;
  12174. this._currentRenderId = this.getScene().getRenderId();
  12175. this._isDirty = false;
  12176. // Scaling
  12177. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  12178. // Rotation
  12179. //rotate, if quaternion is set and rotation was used
  12180. if (this.rotationQuaternion) {
  12181. var len = this.rotation.length();
  12182. if (len) {
  12183. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  12184. this.rotation.copyFromFloats(0, 0, 0);
  12185. }
  12186. }
  12187. if (this.rotationQuaternion) {
  12188. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  12189. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  12190. }
  12191. else {
  12192. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  12193. this._cache.rotation.copyFrom(this.rotation);
  12194. }
  12195. // Translation
  12196. if (this.infiniteDistance && !this.parent) {
  12197. var camera = this.getScene().activeCamera;
  12198. if (camera) {
  12199. var cameraWorldMatrix = camera.getWorldMatrix();
  12200. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  12201. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  12202. }
  12203. }
  12204. else {
  12205. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  12206. }
  12207. // Composing transformations
  12208. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  12209. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12210. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  12211. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  12212. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  12213. // Need to decompose each rotation here
  12214. var currentPosition = BABYLON.Tmp.Vector3[3];
  12215. if (this.parent && this.parent.getWorldMatrix) {
  12216. if (this._meshToBoneReferal) {
  12217. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12218. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  12219. }
  12220. else {
  12221. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  12222. }
  12223. }
  12224. else {
  12225. currentPosition.copyFrom(this.position);
  12226. }
  12227. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  12228. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  12229. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  12230. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  12231. }
  12232. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  12233. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  12234. }
  12235. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  12236. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  12237. }
  12238. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  12239. }
  12240. else {
  12241. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  12242. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  12243. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  12244. }
  12245. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  12246. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12247. }
  12248. // Local world
  12249. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  12250. // Parent
  12251. if (this.parent && this.parent.getWorldMatrix) {
  12252. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  12253. if (this._meshToBoneReferal) {
  12254. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12255. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  12256. }
  12257. else {
  12258. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  12259. }
  12260. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  12261. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  12262. this._worldMatrix.copyFrom(this._localWorld);
  12263. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  12264. }
  12265. else {
  12266. if (this._meshToBoneReferal) {
  12267. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12268. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  12269. }
  12270. else {
  12271. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  12272. }
  12273. }
  12274. this._markSyncedWithParent();
  12275. }
  12276. else {
  12277. this._worldMatrix.copyFrom(this._localWorld);
  12278. }
  12279. // Bounding info
  12280. this._updateBoundingInfo();
  12281. // Absolute position
  12282. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  12283. // Callbacks
  12284. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  12285. if (!this._poseMatrix) {
  12286. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  12287. }
  12288. return this._worldMatrix;
  12289. };
  12290. /**
  12291. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  12292. * @param func: callback function to add
  12293. *
  12294. * Returns the AbstractMesh.
  12295. */
  12296. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  12297. this.onAfterWorldMatrixUpdateObservable.add(func);
  12298. return this;
  12299. };
  12300. /**
  12301. * Removes a registered callback function.
  12302. * Returns the AbstractMesh.
  12303. */
  12304. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  12305. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  12306. return this;
  12307. };
  12308. /**
  12309. * Sets the mesh position in its local space.
  12310. * Returns the AbstractMesh.
  12311. */
  12312. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  12313. this.computeWorldMatrix();
  12314. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  12315. return this;
  12316. };
  12317. /**
  12318. * Returns the mesh position in the local space from the current World matrix values.
  12319. * Returns a new Vector3.
  12320. */
  12321. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  12322. this.computeWorldMatrix();
  12323. var invLocalWorldMatrix = this._localWorld.clone();
  12324. invLocalWorldMatrix.invert();
  12325. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  12326. };
  12327. /**
  12328. * Translates the mesh along the passed Vector3 in its local space.
  12329. * Returns the AbstractMesh.
  12330. */
  12331. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  12332. this.computeWorldMatrix(true);
  12333. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  12334. return this;
  12335. };
  12336. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  12337. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  12338. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  12339. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  12340. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  12341. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  12342. /// <returns>Mesh oriented towards targetMesh</returns>
  12343. if (yawCor === void 0) { yawCor = 0; }
  12344. if (pitchCor === void 0) { pitchCor = 0; }
  12345. if (rollCor === void 0) { rollCor = 0; }
  12346. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12347. var dv = AbstractMesh._lookAtVectorCache;
  12348. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  12349. targetPoint.subtractToRef(pos, dv);
  12350. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  12351. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  12352. var pitch = Math.atan2(dv.y, len);
  12353. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  12354. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  12355. return this;
  12356. };
  12357. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  12358. this._meshToBoneReferal = affectedMesh;
  12359. this.parent = bone;
  12360. if (bone.getWorldMatrix().determinant() < 0) {
  12361. this.scalingDeterminant *= -1;
  12362. }
  12363. return this;
  12364. };
  12365. AbstractMesh.prototype.detachFromBone = function () {
  12366. if (this.parent.getWorldMatrix().determinant() < 0) {
  12367. this.scalingDeterminant *= -1;
  12368. }
  12369. this._meshToBoneReferal = null;
  12370. this.parent = null;
  12371. return this;
  12372. };
  12373. /**
  12374. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  12375. * A mesh is in the frustum if its bounding box intersects the frustum.
  12376. * Boolean returned.
  12377. */
  12378. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  12379. return this._boundingInfo.isInFrustum(frustumPlanes);
  12380. };
  12381. /**
  12382. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  12383. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  12384. * Boolean returned.
  12385. */
  12386. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12387. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  12388. ;
  12389. };
  12390. /**
  12391. * True if the mesh intersects another mesh or a SolidParticle object.
  12392. * 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)
  12393. * Returns a boolean.
  12394. */
  12395. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  12396. if (!this._boundingInfo || !mesh._boundingInfo) {
  12397. return false;
  12398. }
  12399. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  12400. };
  12401. /**
  12402. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  12403. * Returns a boolean.
  12404. */
  12405. AbstractMesh.prototype.intersectsPoint = function (point) {
  12406. if (!this._boundingInfo) {
  12407. return false;
  12408. }
  12409. return this._boundingInfo.intersectsPoint(point);
  12410. };
  12411. AbstractMesh.prototype.getPhysicsImpostor = function () {
  12412. return this.physicsImpostor;
  12413. };
  12414. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  12415. if (!camera) {
  12416. camera = this.getScene().activeCamera;
  12417. }
  12418. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  12419. };
  12420. /**
  12421. * Returns the distance from the mesh to the active camera.
  12422. * Returns a float.
  12423. */
  12424. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  12425. if (!camera) {
  12426. camera = this.getScene().activeCamera;
  12427. }
  12428. return this.absolutePosition.subtract(camera.position).length();
  12429. };
  12430. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  12431. if (!this.physicsImpostor) {
  12432. return;
  12433. }
  12434. this.physicsImpostor.applyImpulse(force, contactPoint);
  12435. return this;
  12436. };
  12437. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  12438. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  12439. return;
  12440. }
  12441. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  12442. mainPivot: pivot1,
  12443. connectedPivot: pivot2,
  12444. nativeParams: options
  12445. });
  12446. return this;
  12447. };
  12448. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  12449. // Collisions
  12450. /**
  12451. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  12452. * Default `false`.
  12453. */
  12454. get: function () {
  12455. return this._checkCollisions;
  12456. },
  12457. set: function (collisionEnabled) {
  12458. this._checkCollisions = collisionEnabled;
  12459. if (this.getScene().workerCollisions) {
  12460. this.getScene().collisionCoordinator.onMeshUpdated(this);
  12461. }
  12462. },
  12463. enumerable: true,
  12464. configurable: true
  12465. });
  12466. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  12467. var globalPosition = this.getAbsolutePosition();
  12468. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  12469. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  12470. if (!this._collider) {
  12471. this._collider = new BABYLON.Collider();
  12472. }
  12473. this._collider.radius = this.ellipsoid;
  12474. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  12475. return this;
  12476. };
  12477. // Submeshes octree
  12478. /**
  12479. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  12480. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  12481. * Returns an Octree of submeshes.
  12482. */
  12483. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  12484. if (maxCapacity === void 0) { maxCapacity = 64; }
  12485. if (maxDepth === void 0) { maxDepth = 2; }
  12486. if (!this._submeshesOctree) {
  12487. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  12488. }
  12489. this.computeWorldMatrix(true);
  12490. // Update octree
  12491. var bbox = this.getBoundingInfo().boundingBox;
  12492. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  12493. return this._submeshesOctree;
  12494. };
  12495. // Collisions
  12496. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  12497. this._generatePointsArray();
  12498. // Transformation
  12499. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  12500. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  12501. subMesh._lastColliderWorldVertices = [];
  12502. subMesh._trianglePlanes = [];
  12503. var start = subMesh.verticesStart;
  12504. var end = (subMesh.verticesStart + subMesh.verticesCount);
  12505. for (var i = start; i < end; i++) {
  12506. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  12507. }
  12508. }
  12509. // Collide
  12510. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  12511. if (collider.collisionFound) {
  12512. collider.collidedMesh = this;
  12513. }
  12514. return this;
  12515. };
  12516. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  12517. var subMeshes;
  12518. var len;
  12519. // Octrees
  12520. if (this._submeshesOctree && this.useOctreeForCollisions) {
  12521. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  12522. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  12523. len = intersections.length;
  12524. subMeshes = intersections.data;
  12525. }
  12526. else {
  12527. subMeshes = this.subMeshes;
  12528. len = subMeshes.length;
  12529. }
  12530. for (var index = 0; index < len; index++) {
  12531. var subMesh = subMeshes[index];
  12532. // Bounding test
  12533. if (len > 1 && !subMesh._checkCollision(collider))
  12534. continue;
  12535. this._collideForSubMesh(subMesh, transformMatrix, collider);
  12536. }
  12537. return this;
  12538. };
  12539. AbstractMesh.prototype._checkCollision = function (collider) {
  12540. // Bounding box test
  12541. if (!this._boundingInfo._checkCollision(collider))
  12542. return this;
  12543. // Transformation matrix
  12544. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  12545. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  12546. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  12547. return this;
  12548. };
  12549. // Picking
  12550. AbstractMesh.prototype._generatePointsArray = function () {
  12551. return false;
  12552. };
  12553. /**
  12554. * Checks if the passed Ray intersects with the mesh.
  12555. * Returns an object PickingInfo.
  12556. */
  12557. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  12558. var pickingInfo = new BABYLON.PickingInfo();
  12559. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  12560. return pickingInfo;
  12561. }
  12562. if (!this._generatePointsArray()) {
  12563. return pickingInfo;
  12564. }
  12565. var intersectInfo = null;
  12566. // Octrees
  12567. var subMeshes;
  12568. var len;
  12569. if (this._submeshesOctree && this.useOctreeForPicking) {
  12570. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  12571. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  12572. len = intersections.length;
  12573. subMeshes = intersections.data;
  12574. }
  12575. else {
  12576. subMeshes = this.subMeshes;
  12577. len = subMeshes.length;
  12578. }
  12579. for (var index = 0; index < len; index++) {
  12580. var subMesh = subMeshes[index];
  12581. // Bounding test
  12582. if (len > 1 && !subMesh.canIntersects(ray))
  12583. continue;
  12584. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  12585. if (currentIntersectInfo) {
  12586. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12587. intersectInfo = currentIntersectInfo;
  12588. intersectInfo.subMeshId = index;
  12589. if (fastCheck) {
  12590. break;
  12591. }
  12592. }
  12593. }
  12594. }
  12595. if (intersectInfo) {
  12596. // Get picked point
  12597. var world = this.getWorldMatrix();
  12598. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  12599. var direction = ray.direction.clone();
  12600. direction = direction.scale(intersectInfo.distance);
  12601. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  12602. var pickedPoint = worldOrigin.add(worldDirection);
  12603. // Return result
  12604. pickingInfo.hit = true;
  12605. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  12606. pickingInfo.pickedPoint = pickedPoint;
  12607. pickingInfo.pickedMesh = this;
  12608. pickingInfo.bu = intersectInfo.bu;
  12609. pickingInfo.bv = intersectInfo.bv;
  12610. pickingInfo.faceId = intersectInfo.faceId;
  12611. pickingInfo.subMeshId = intersectInfo.subMeshId;
  12612. return pickingInfo;
  12613. }
  12614. return pickingInfo;
  12615. };
  12616. /**
  12617. * Clones the mesh, used by the class Mesh.
  12618. * Just returns `null` for an AbstractMesh.
  12619. */
  12620. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12621. return null;
  12622. };
  12623. /**
  12624. * Disposes all the mesh submeshes.
  12625. * Returns the AbstractMesh.
  12626. */
  12627. AbstractMesh.prototype.releaseSubMeshes = function () {
  12628. if (this.subMeshes) {
  12629. while (this.subMeshes.length) {
  12630. this.subMeshes[0].dispose();
  12631. }
  12632. }
  12633. else {
  12634. this.subMeshes = new Array();
  12635. }
  12636. return this;
  12637. };
  12638. /**
  12639. * Disposes the AbstractMesh.
  12640. * Some internal references are kept for further use.
  12641. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  12642. * Returns nothing.
  12643. */
  12644. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  12645. var _this = this;
  12646. var index;
  12647. // Action manager
  12648. if (this.actionManager) {
  12649. this.actionManager.dispose();
  12650. this.actionManager = null;
  12651. }
  12652. // Skeleton
  12653. this.skeleton = null;
  12654. // Animations
  12655. this.getScene().stopAnimation(this);
  12656. // Physics
  12657. if (this.physicsImpostor) {
  12658. this.physicsImpostor.dispose();
  12659. }
  12660. // Intersections in progress
  12661. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  12662. var other = this._intersectionsInProgress[index];
  12663. var pos = other._intersectionsInProgress.indexOf(this);
  12664. other._intersectionsInProgress.splice(pos, 1);
  12665. }
  12666. this._intersectionsInProgress = [];
  12667. // Lights
  12668. var lights = this.getScene().lights;
  12669. lights.forEach(function (light) {
  12670. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  12671. if (meshIndex !== -1) {
  12672. light.includedOnlyMeshes.splice(meshIndex, 1);
  12673. }
  12674. meshIndex = light.excludedMeshes.indexOf(_this);
  12675. if (meshIndex !== -1) {
  12676. light.excludedMeshes.splice(meshIndex, 1);
  12677. }
  12678. // Shadow generators
  12679. var generator = light.getShadowGenerator();
  12680. if (generator) {
  12681. var shadowMap = generator.getShadowMap();
  12682. meshIndex = shadowMap.renderList.indexOf(_this);
  12683. if (meshIndex !== -1) {
  12684. shadowMap.renderList.splice(meshIndex, 1);
  12685. }
  12686. }
  12687. });
  12688. // Edges
  12689. if (this._edgesRenderer) {
  12690. this._edgesRenderer.dispose();
  12691. this._edgesRenderer = null;
  12692. }
  12693. // SubMeshes
  12694. if (this.getClassName() !== "InstancedMesh") {
  12695. this.releaseSubMeshes();
  12696. }
  12697. // Octree
  12698. var sceneOctree = this.getScene().selectionOctree;
  12699. if (sceneOctree) {
  12700. var index = sceneOctree.dynamicContent.indexOf(this);
  12701. if (index !== -1) {
  12702. sceneOctree.dynamicContent.splice(index, 1);
  12703. }
  12704. }
  12705. // Engine
  12706. this.getScene().getEngine().wipeCaches();
  12707. // Remove from scene
  12708. this.getScene().removeMesh(this);
  12709. if (!doNotRecurse) {
  12710. // Particles
  12711. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  12712. if (this.getScene().particleSystems[index].emitter === this) {
  12713. this.getScene().particleSystems[index].dispose();
  12714. index--;
  12715. }
  12716. }
  12717. // Children
  12718. var objects = this.getDescendants(true);
  12719. for (index = 0; index < objects.length; index++) {
  12720. objects[index].dispose();
  12721. }
  12722. }
  12723. else {
  12724. var childMeshes = this.getChildMeshes(true);
  12725. for (index = 0; index < childMeshes.length; index++) {
  12726. var child = childMeshes[index];
  12727. child.parent = null;
  12728. child.computeWorldMatrix(true);
  12729. }
  12730. }
  12731. // facet data
  12732. if (this._facetDataEnabled) {
  12733. this.disableFacetData();
  12734. }
  12735. this.onAfterWorldMatrixUpdateObservable.clear();
  12736. this.onCollideObservable.clear();
  12737. this.onCollisionPositionChangeObservable.clear();
  12738. this._isDisposed = true;
  12739. _super.prototype.dispose.call(this);
  12740. };
  12741. /**
  12742. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  12743. * This Vector3 is expressed in the World space.
  12744. */
  12745. AbstractMesh.prototype.getDirection = function (localAxis) {
  12746. var result = BABYLON.Vector3.Zero();
  12747. this.getDirectionToRef(localAxis, result);
  12748. return result;
  12749. };
  12750. /**
  12751. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  12752. * localAxis is expressed in the mesh local space.
  12753. * result is computed in the Wordl space from the mesh World matrix.
  12754. * Returns the AbstractMesh.
  12755. */
  12756. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  12757. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  12758. return this;
  12759. };
  12760. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  12761. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12762. if (this.getScene().getRenderId() == 0) {
  12763. this.computeWorldMatrix(true);
  12764. }
  12765. var wm = this.getWorldMatrix();
  12766. if (space == BABYLON.Space.WORLD) {
  12767. var tmat = BABYLON.Tmp.Matrix[0];
  12768. wm.invertToRef(tmat);
  12769. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  12770. }
  12771. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  12772. this._pivotMatrix.m[12] = -point.x;
  12773. this._pivotMatrix.m[13] = -point.y;
  12774. this._pivotMatrix.m[14] = -point.z;
  12775. this._cache.pivotMatrixUpdated = true;
  12776. return this;
  12777. };
  12778. /**
  12779. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  12780. */
  12781. AbstractMesh.prototype.getPivotPoint = function () {
  12782. var point = BABYLON.Vector3.Zero();
  12783. this.getPivotPointToRef(point);
  12784. return point;
  12785. };
  12786. /**
  12787. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  12788. * Returns the AbstractMesh.
  12789. */
  12790. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  12791. result.x = -this._pivotMatrix.m[12];
  12792. result.y = -this._pivotMatrix.m[13];
  12793. result.z = -this._pivotMatrix.m[14];
  12794. return this;
  12795. };
  12796. /**
  12797. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  12798. */
  12799. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  12800. var point = BABYLON.Vector3.Zero();
  12801. this.getAbsolutePivotPointToRef(point);
  12802. return point;
  12803. };
  12804. /**
  12805. * Defines the passed mesh as the parent of the current mesh.
  12806. * Returns the AbstractMesh.
  12807. */
  12808. AbstractMesh.prototype.setParent = function (mesh) {
  12809. var child = this;
  12810. var parent = mesh;
  12811. if (mesh == null) {
  12812. var rotation = BABYLON.Tmp.Quaternion[0];
  12813. var position = BABYLON.Tmp.Vector3[0];
  12814. var scale = BABYLON.Tmp.Vector3[1];
  12815. child.getWorldMatrix().decompose(scale, rotation, position);
  12816. if (child.rotationQuaternion) {
  12817. child.rotationQuaternion.copyFrom(rotation);
  12818. }
  12819. else {
  12820. rotation.toEulerAnglesToRef(child.rotation);
  12821. }
  12822. child.position.x = position.x;
  12823. child.position.y = position.y;
  12824. child.position.z = position.z;
  12825. }
  12826. else {
  12827. var rotation = BABYLON.Tmp.Quaternion[0];
  12828. var position = BABYLON.Tmp.Vector3[0];
  12829. var scale = BABYLON.Tmp.Vector3[1];
  12830. var m1 = BABYLON.Tmp.Matrix[0];
  12831. var m2 = BABYLON.Tmp.Matrix[1];
  12832. parent.getWorldMatrix().decompose(scale, rotation, position);
  12833. rotation.toRotationMatrix(m1);
  12834. m2.setTranslation(position);
  12835. m2.multiplyToRef(m1, m1);
  12836. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  12837. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12838. m.decompose(scale, rotation, position);
  12839. if (child.rotationQuaternion) {
  12840. child.rotationQuaternion.copyFrom(rotation);
  12841. }
  12842. else {
  12843. rotation.toEulerAnglesToRef(child.rotation);
  12844. }
  12845. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  12846. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12847. m.decompose(scale, rotation, position);
  12848. child.position.x = position.x;
  12849. child.position.y = position.y;
  12850. child.position.z = position.z;
  12851. }
  12852. child.parent = parent;
  12853. return this;
  12854. };
  12855. /**
  12856. * Adds the passed mesh as a child to the current mesh.
  12857. * Returns the AbstractMesh.
  12858. */
  12859. AbstractMesh.prototype.addChild = function (mesh) {
  12860. mesh.setParent(this);
  12861. return this;
  12862. };
  12863. /**
  12864. * Removes the passed mesh from the current mesh children list.
  12865. * Returns the AbstractMesh.
  12866. */
  12867. AbstractMesh.prototype.removeChild = function (mesh) {
  12868. mesh.setParent(null);
  12869. return this;
  12870. };
  12871. /**
  12872. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  12873. * Returns the AbstractMesh.
  12874. */
  12875. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  12876. result.x = this._pivotMatrix.m[12];
  12877. result.y = this._pivotMatrix.m[13];
  12878. result.z = this._pivotMatrix.m[14];
  12879. this.getPivotPointToRef(result);
  12880. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  12881. return this;
  12882. };
  12883. // Facet data
  12884. /**
  12885. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  12886. * Returns the AbstractMesh.
  12887. */
  12888. AbstractMesh.prototype._initFacetData = function () {
  12889. if (!this._facetNormals) {
  12890. this._facetNormals = new Array();
  12891. }
  12892. if (!this._facetPositions) {
  12893. this._facetPositions = new Array();
  12894. }
  12895. if (!this._facetPartitioning) {
  12896. this._facetPartitioning = new Array();
  12897. }
  12898. this._facetNb = this.getIndices().length / 3;
  12899. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  12900. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  12901. for (var f = 0; f < this._facetNb; f++) {
  12902. this._facetNormals[f] = BABYLON.Vector3.Zero();
  12903. this._facetPositions[f] = BABYLON.Vector3.Zero();
  12904. }
  12905. this._facetDataEnabled = true;
  12906. return this;
  12907. };
  12908. /**
  12909. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  12910. * This method can be called within the render loop.
  12911. * 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.
  12912. * Returns the AbstractMesh.
  12913. */
  12914. AbstractMesh.prototype.updateFacetData = function () {
  12915. if (!this._facetDataEnabled) {
  12916. this._initFacetData();
  12917. }
  12918. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12919. var indices = this.getIndices();
  12920. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12921. var bInfo = this.getBoundingInfo();
  12922. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  12923. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  12924. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  12925. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  12926. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  12927. this._subDiv.max = this._partitioningSubdivisions;
  12928. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  12929. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  12930. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  12931. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  12932. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  12933. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  12934. // set the parameters for ComputeNormals()
  12935. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  12936. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  12937. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  12938. this._facetParameters.bInfo = bInfo;
  12939. this._facetParameters.bbSize = this._bbSize;
  12940. this._facetParameters.subDiv = this._subDiv;
  12941. this._facetParameters.ratio = this.partitioningBBoxRatio;
  12942. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  12943. return this;
  12944. };
  12945. /**
  12946. * Returns the facetLocalNormals array.
  12947. * The normals are expressed in the mesh local space.
  12948. */
  12949. AbstractMesh.prototype.getFacetLocalNormals = function () {
  12950. if (!this._facetNormals) {
  12951. this.updateFacetData();
  12952. }
  12953. return this._facetNormals;
  12954. };
  12955. /**
  12956. * Returns the facetLocalPositions array.
  12957. * The facet positions are expressed in the mesh local space.
  12958. */
  12959. AbstractMesh.prototype.getFacetLocalPositions = function () {
  12960. if (!this._facetPositions) {
  12961. this.updateFacetData();
  12962. }
  12963. return this._facetPositions;
  12964. };
  12965. /**
  12966. * Returns the facetLocalPartioning array.
  12967. */
  12968. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  12969. if (!this._facetPartitioning) {
  12970. this.updateFacetData();
  12971. }
  12972. return this._facetPartitioning;
  12973. };
  12974. /**
  12975. * Returns the i-th facet position in the world system.
  12976. * This method allocates a new Vector3 per call.
  12977. */
  12978. AbstractMesh.prototype.getFacetPosition = function (i) {
  12979. var pos = BABYLON.Vector3.Zero();
  12980. this.getFacetPositionToRef(i, pos);
  12981. return pos;
  12982. };
  12983. /**
  12984. * Sets the reference Vector3 with the i-th facet position in the world system.
  12985. * Returns the AbstractMesh.
  12986. */
  12987. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  12988. var localPos = (this.getFacetLocalPositions())[i];
  12989. var world = this.getWorldMatrix();
  12990. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  12991. return this;
  12992. };
  12993. /**
  12994. * Returns the i-th facet normal in the world system.
  12995. * This method allocates a new Vector3 per call.
  12996. */
  12997. AbstractMesh.prototype.getFacetNormal = function (i) {
  12998. var norm = BABYLON.Vector3.Zero();
  12999. this.getFacetNormalToRef(i, norm);
  13000. return norm;
  13001. };
  13002. /**
  13003. * Sets the reference Vector3 with the i-th facet normal in the world system.
  13004. * Returns the AbstractMesh.
  13005. */
  13006. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  13007. var localNorm = (this.getFacetLocalNormals())[i];
  13008. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  13009. return this;
  13010. };
  13011. /**
  13012. * 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).
  13013. */
  13014. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  13015. var bInfo = this.getBoundingInfo();
  13016. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  13017. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  13018. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  13019. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  13020. return null;
  13021. }
  13022. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  13023. };
  13024. /**
  13025. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  13026. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  13027. * 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.
  13028. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13029. * 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.
  13030. */
  13031. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  13032. if (checkFace === void 0) { checkFace = false; }
  13033. if (facing === void 0) { facing = true; }
  13034. var world = this.getWorldMatrix();
  13035. var invMat = BABYLON.Tmp.Matrix[5];
  13036. world.invertToRef(invMat);
  13037. var invVect = BABYLON.Tmp.Vector3[8];
  13038. var closest = null;
  13039. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  13040. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  13041. if (projected) {
  13042. // tranform the local computed projected vector to world coordinates
  13043. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  13044. }
  13045. return closest;
  13046. };
  13047. /**
  13048. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  13049. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  13050. * 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.
  13051. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13052. * 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.
  13053. */
  13054. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  13055. if (checkFace === void 0) { checkFace = false; }
  13056. if (facing === void 0) { facing = true; }
  13057. var closest = null;
  13058. var tmpx = 0.0;
  13059. var tmpy = 0.0;
  13060. var tmpz = 0.0;
  13061. var d = 0.0; // tmp dot facet normal * facet position
  13062. var t0 = 0.0;
  13063. var projx = 0.0;
  13064. var projy = 0.0;
  13065. var projz = 0.0;
  13066. // Get all the facets in the same partitioning block than (x, y, z)
  13067. var facetPositions = this.getFacetLocalPositions();
  13068. var facetNormals = this.getFacetLocalNormals();
  13069. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  13070. if (!facetsInBlock) {
  13071. return null;
  13072. }
  13073. // Get the closest facet to (x, y, z)
  13074. var shortest = Number.MAX_VALUE; // init distance vars
  13075. var tmpDistance = shortest;
  13076. var fib; // current facet in the block
  13077. var norm; // current facet normal
  13078. var p0; // current facet barycenter position
  13079. // loop on all the facets in the current partitioning block
  13080. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  13081. fib = facetsInBlock[idx];
  13082. norm = facetNormals[fib];
  13083. p0 = facetPositions[fib];
  13084. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  13085. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  13086. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  13087. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  13088. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  13089. projx = x + norm.x * t0;
  13090. projy = y + norm.y * t0;
  13091. projz = z + norm.z * t0;
  13092. tmpx = projx - x;
  13093. tmpy = projy - y;
  13094. tmpz = projz - z;
  13095. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13096. if (tmpDistance < shortest) {
  13097. shortest = tmpDistance;
  13098. closest = fib;
  13099. if (projected) {
  13100. projected.x = projx;
  13101. projected.y = projy;
  13102. projected.z = projz;
  13103. }
  13104. }
  13105. }
  13106. }
  13107. return closest;
  13108. };
  13109. /**
  13110. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13111. */
  13112. AbstractMesh.prototype.getFacetDataParameters = function () {
  13113. return this._facetParameters;
  13114. };
  13115. /**
  13116. * Disables the feature FacetData and frees the related memory.
  13117. * Returns the AbstractMesh.
  13118. */
  13119. AbstractMesh.prototype.disableFacetData = function () {
  13120. if (this._facetDataEnabled) {
  13121. this._facetDataEnabled = false;
  13122. this._facetPositions = null;
  13123. this._facetNormals = null;
  13124. this._facetPartitioning = null;
  13125. this._facetParameters = null;
  13126. }
  13127. return this;
  13128. };
  13129. /**
  13130. * Creates new normals data for the mesh.
  13131. * @param updatable.
  13132. */
  13133. AbstractMesh.prototype.createNormals = function (updatable) {
  13134. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13135. var indices = this.getIndices();
  13136. var normals;
  13137. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13138. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13139. }
  13140. else {
  13141. normals = [];
  13142. }
  13143. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  13144. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  13145. };
  13146. return AbstractMesh;
  13147. }(BABYLON.Node));
  13148. // Statics
  13149. AbstractMesh._BILLBOARDMODE_NONE = 0;
  13150. AbstractMesh._BILLBOARDMODE_X = 1;
  13151. AbstractMesh._BILLBOARDMODE_Y = 2;
  13152. AbstractMesh._BILLBOARDMODE_Z = 4;
  13153. AbstractMesh._BILLBOARDMODE_ALL = 7;
  13154. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  13155. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  13156. BABYLON.AbstractMesh = AbstractMesh;
  13157. })(BABYLON || (BABYLON = {}));
  13158. //# sourceMappingURL=babylon.abstractMesh.js.map
  13159. var BABYLON;
  13160. (function (BABYLON) {
  13161. var Light = (function (_super) {
  13162. __extends(Light, _super);
  13163. /**
  13164. * Creates a Light object in the scene.
  13165. * Documentation : http://doc.babylonjs.com/tutorials/lights
  13166. */
  13167. function Light(name, scene) {
  13168. var _this = _super.call(this, name, scene) || this;
  13169. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  13170. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  13171. _this.intensity = 1.0;
  13172. _this.range = Number.MAX_VALUE;
  13173. /**
  13174. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  13175. * of light.
  13176. */
  13177. _this._photometricScale = 1.0;
  13178. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  13179. _this._radius = 0.00001;
  13180. _this.renderPriority = 0;
  13181. /**
  13182. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  13183. * the current shadow generator.
  13184. */
  13185. _this.shadowEnabled = true;
  13186. _this._excludeWithLayerMask = 0;
  13187. _this._includeOnlyWithLayerMask = 0;
  13188. _this._lightmapMode = 0;
  13189. _this._excludedMeshesIds = new Array();
  13190. _this._includedOnlyMeshesIds = new Array();
  13191. _this.getScene().addLight(_this);
  13192. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  13193. _this._buildUniformLayout();
  13194. _this.includedOnlyMeshes = new Array();
  13195. _this.excludedMeshes = new Array();
  13196. _this._resyncMeshes();
  13197. return _this;
  13198. }
  13199. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  13200. /**
  13201. * If every light affecting the material is in this lightmapMode,
  13202. * material.lightmapTexture adds or multiplies
  13203. * (depends on material.useLightmapAsShadowmap)
  13204. * after every other light calculations.
  13205. */
  13206. get: function () {
  13207. return Light._LIGHTMAP_DEFAULT;
  13208. },
  13209. enumerable: true,
  13210. configurable: true
  13211. });
  13212. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  13213. /**
  13214. * material.lightmapTexture as only diffuse lighting from this light
  13215. * adds pnly specular lighting from this light
  13216. * adds dynamic shadows
  13217. */
  13218. get: function () {
  13219. return Light._LIGHTMAP_SPECULAR;
  13220. },
  13221. enumerable: true,
  13222. configurable: true
  13223. });
  13224. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  13225. /**
  13226. * material.lightmapTexture as only lighting
  13227. * no light calculation from this light
  13228. * only adds dynamic shadows from this light
  13229. */
  13230. get: function () {
  13231. return Light._LIGHTMAP_SHADOWSONLY;
  13232. },
  13233. enumerable: true,
  13234. configurable: true
  13235. });
  13236. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  13237. /**
  13238. * Each light type uses the default quantity according to its type:
  13239. * point/spot lights use luminous intensity
  13240. * directional lights use illuminance
  13241. */
  13242. get: function () {
  13243. return Light._INTENSITYMODE_AUTOMATIC;
  13244. },
  13245. enumerable: true,
  13246. configurable: true
  13247. });
  13248. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  13249. /**
  13250. * lumen (lm)
  13251. */
  13252. get: function () {
  13253. return Light._INTENSITYMODE_LUMINOUSPOWER;
  13254. },
  13255. enumerable: true,
  13256. configurable: true
  13257. });
  13258. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  13259. /**
  13260. * candela (lm/sr)
  13261. */
  13262. get: function () {
  13263. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  13264. },
  13265. enumerable: true,
  13266. configurable: true
  13267. });
  13268. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  13269. /**
  13270. * lux (lm/m^2)
  13271. */
  13272. get: function () {
  13273. return Light._INTENSITYMODE_ILLUMINANCE;
  13274. },
  13275. enumerable: true,
  13276. configurable: true
  13277. });
  13278. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  13279. /**
  13280. * nit (cd/m^2)
  13281. */
  13282. get: function () {
  13283. return Light._INTENSITYMODE_LUMINANCE;
  13284. },
  13285. enumerable: true,
  13286. configurable: true
  13287. });
  13288. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  13289. /**
  13290. * Light type const id of the point light.
  13291. */
  13292. get: function () {
  13293. return Light._LIGHTTYPEID_POINTLIGHT;
  13294. },
  13295. enumerable: true,
  13296. configurable: true
  13297. });
  13298. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  13299. /**
  13300. * Light type const id of the directional light.
  13301. */
  13302. get: function () {
  13303. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  13304. },
  13305. enumerable: true,
  13306. configurable: true
  13307. });
  13308. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  13309. /**
  13310. * Light type const id of the spot light.
  13311. */
  13312. get: function () {
  13313. return Light._LIGHTTYPEID_SPOTLIGHT;
  13314. },
  13315. enumerable: true,
  13316. configurable: true
  13317. });
  13318. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  13319. /**
  13320. * Light type const id of the hemispheric light.
  13321. */
  13322. get: function () {
  13323. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  13324. },
  13325. enumerable: true,
  13326. configurable: true
  13327. });
  13328. Object.defineProperty(Light.prototype, "intensityMode", {
  13329. /**
  13330. * Gets the photometric scale used to interpret the intensity.
  13331. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13332. */
  13333. get: function () {
  13334. return this._intensityMode;
  13335. },
  13336. /**
  13337. * Sets the photometric scale used to interpret the intensity.
  13338. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13339. */
  13340. set: function (value) {
  13341. this._intensityMode = value;
  13342. this._computePhotometricScale();
  13343. },
  13344. enumerable: true,
  13345. configurable: true
  13346. });
  13347. ;
  13348. ;
  13349. Object.defineProperty(Light.prototype, "radius", {
  13350. /**
  13351. * Gets the light radius used by PBR Materials to simulate soft area lights.
  13352. */
  13353. get: function () {
  13354. return this._radius;
  13355. },
  13356. /**
  13357. * sets the light radius used by PBR Materials to simulate soft area lights.
  13358. */
  13359. set: function (value) {
  13360. this._radius = value;
  13361. this._computePhotometricScale();
  13362. },
  13363. enumerable: true,
  13364. configurable: true
  13365. });
  13366. ;
  13367. ;
  13368. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  13369. get: function () {
  13370. return this._includedOnlyMeshes;
  13371. },
  13372. set: function (value) {
  13373. this._includedOnlyMeshes = value;
  13374. this._hookArrayForIncludedOnly(value);
  13375. },
  13376. enumerable: true,
  13377. configurable: true
  13378. });
  13379. Object.defineProperty(Light.prototype, "excludedMeshes", {
  13380. get: function () {
  13381. return this._excludedMeshes;
  13382. },
  13383. set: function (value) {
  13384. this._excludedMeshes = value;
  13385. this._hookArrayForExcluded(value);
  13386. },
  13387. enumerable: true,
  13388. configurable: true
  13389. });
  13390. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  13391. get: function () {
  13392. return this._excludeWithLayerMask;
  13393. },
  13394. set: function (value) {
  13395. this._excludeWithLayerMask = value;
  13396. this._resyncMeshes();
  13397. },
  13398. enumerable: true,
  13399. configurable: true
  13400. });
  13401. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  13402. get: function () {
  13403. return this._includeOnlyWithLayerMask;
  13404. },
  13405. set: function (value) {
  13406. this._includeOnlyWithLayerMask = value;
  13407. this._resyncMeshes();
  13408. },
  13409. enumerable: true,
  13410. configurable: true
  13411. });
  13412. Object.defineProperty(Light.prototype, "lightmapMode", {
  13413. get: function () {
  13414. return this._lightmapMode;
  13415. },
  13416. set: function (value) {
  13417. if (this._lightmapMode === value) {
  13418. return;
  13419. }
  13420. this._lightmapMode = value;
  13421. this._markMeshesAsLightDirty();
  13422. },
  13423. enumerable: true,
  13424. configurable: true
  13425. });
  13426. Light.prototype._buildUniformLayout = function () {
  13427. // Overridden
  13428. };
  13429. /**
  13430. * Returns the string "Light".
  13431. */
  13432. Light.prototype.getClassName = function () {
  13433. return "Light";
  13434. };
  13435. /**
  13436. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13437. */
  13438. Light.prototype.toString = function (fullDetails) {
  13439. var ret = "Name: " + this.name;
  13440. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  13441. if (this.animations) {
  13442. for (var i = 0; i < this.animations.length; i++) {
  13443. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13444. }
  13445. }
  13446. if (fullDetails) {
  13447. }
  13448. return ret;
  13449. };
  13450. /**
  13451. * Set the enabled state of this node.
  13452. * @param {boolean} value - the new enabled state
  13453. * @see isEnabled
  13454. */
  13455. Light.prototype.setEnabled = function (value) {
  13456. _super.prototype.setEnabled.call(this, value);
  13457. this._resyncMeshes();
  13458. };
  13459. /**
  13460. * Returns the Light associated shadow generator.
  13461. */
  13462. Light.prototype.getShadowGenerator = function () {
  13463. return this._shadowGenerator;
  13464. };
  13465. /**
  13466. * Returns a Vector3, the absolute light position in the World.
  13467. */
  13468. Light.prototype.getAbsolutePosition = function () {
  13469. return BABYLON.Vector3.Zero();
  13470. };
  13471. Light.prototype.transferToEffect = function (effect, lightIndex) {
  13472. };
  13473. Light.prototype._getWorldMatrix = function () {
  13474. return BABYLON.Matrix.Identity();
  13475. };
  13476. /**
  13477. * Boolean : True if the light will affect the passed mesh.
  13478. */
  13479. Light.prototype.canAffectMesh = function (mesh) {
  13480. if (!mesh) {
  13481. return true;
  13482. }
  13483. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  13484. return false;
  13485. }
  13486. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  13487. return false;
  13488. }
  13489. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  13490. return false;
  13491. }
  13492. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  13493. return false;
  13494. }
  13495. return true;
  13496. };
  13497. /**
  13498. * Returns the light World matrix.
  13499. */
  13500. Light.prototype.getWorldMatrix = function () {
  13501. this._currentRenderId = this.getScene().getRenderId();
  13502. var worldMatrix = this._getWorldMatrix();
  13503. if (this.parent && this.parent.getWorldMatrix) {
  13504. if (!this._parentedWorldMatrix) {
  13505. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  13506. }
  13507. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  13508. this._markSyncedWithParent();
  13509. return this._parentedWorldMatrix;
  13510. }
  13511. return worldMatrix;
  13512. };
  13513. /**
  13514. * Sort function to order lights for rendering.
  13515. * @param a First Light object to compare to second.
  13516. * @param b Second Light object to compare first.
  13517. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  13518. */
  13519. Light.compareLightsPriority = function (a, b) {
  13520. //shadow-casting lights have priority over non-shadow-casting lights
  13521. //the renderPrioirty is a secondary sort criterion
  13522. if (a.shadowEnabled !== b.shadowEnabled) {
  13523. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  13524. }
  13525. return b.renderPriority - a.renderPriority;
  13526. };
  13527. /**
  13528. * Disposes the light.
  13529. */
  13530. Light.prototype.dispose = function () {
  13531. if (this._shadowGenerator) {
  13532. this._shadowGenerator.dispose();
  13533. this._shadowGenerator = null;
  13534. }
  13535. // Animations
  13536. this.getScene().stopAnimation(this);
  13537. // Remove from meshes
  13538. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13539. var mesh = _a[_i];
  13540. mesh._removeLightSource(this);
  13541. }
  13542. this._uniformBuffer.dispose();
  13543. // Remove from scene
  13544. this.getScene().removeLight(this);
  13545. _super.prototype.dispose.call(this);
  13546. };
  13547. /**
  13548. * Returns the light type ID (integer).
  13549. */
  13550. Light.prototype.getTypeID = function () {
  13551. return 0;
  13552. };
  13553. /**
  13554. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  13555. */
  13556. Light.prototype.getScaledIntensity = function () {
  13557. return this._photometricScale * this.intensity;
  13558. };
  13559. /**
  13560. * Returns a new Light object, named "name", from the current one.
  13561. */
  13562. Light.prototype.clone = function (name) {
  13563. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  13564. };
  13565. /**
  13566. * Serializes the current light into a Serialization object.
  13567. * Returns the serialized object.
  13568. */
  13569. Light.prototype.serialize = function () {
  13570. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13571. // Type
  13572. serializationObject.type = this.getTypeID();
  13573. // Parent
  13574. if (this.parent) {
  13575. serializationObject.parentId = this.parent.id;
  13576. }
  13577. // Inclusion / exclusions
  13578. if (this.excludedMeshes.length > 0) {
  13579. serializationObject.excludedMeshesIds = [];
  13580. this.excludedMeshes.forEach(function (mesh) {
  13581. serializationObject.excludedMeshesIds.push(mesh.id);
  13582. });
  13583. }
  13584. if (this.includedOnlyMeshes.length > 0) {
  13585. serializationObject.includedOnlyMeshesIds = [];
  13586. this.includedOnlyMeshes.forEach(function (mesh) {
  13587. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  13588. });
  13589. }
  13590. // Animations
  13591. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13592. serializationObject.ranges = this.serializeAnimationRanges();
  13593. return serializationObject;
  13594. };
  13595. /**
  13596. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  13597. * This new light is named "name" and added to the passed scene.
  13598. */
  13599. Light.GetConstructorFromName = function (type, name, scene) {
  13600. switch (type) {
  13601. case 0:
  13602. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  13603. case 1:
  13604. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  13605. case 2:
  13606. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  13607. case 3:
  13608. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  13609. }
  13610. };
  13611. /**
  13612. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  13613. */
  13614. Light.Parse = function (parsedLight, scene) {
  13615. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  13616. // Inclusion / exclusions
  13617. if (parsedLight.excludedMeshesIds) {
  13618. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  13619. }
  13620. if (parsedLight.includedOnlyMeshesIds) {
  13621. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  13622. }
  13623. // Parent
  13624. if (parsedLight.parentId) {
  13625. light._waitingParentId = parsedLight.parentId;
  13626. }
  13627. // Animations
  13628. if (parsedLight.animations) {
  13629. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  13630. var parsedAnimation = parsedLight.animations[animationIndex];
  13631. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13632. }
  13633. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  13634. }
  13635. if (parsedLight.autoAnimate) {
  13636. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  13637. }
  13638. return light;
  13639. };
  13640. Light.prototype._hookArrayForExcluded = function (array) {
  13641. var _this = this;
  13642. var oldPush = array.push;
  13643. array.push = function () {
  13644. var items = [];
  13645. for (var _i = 0; _i < arguments.length; _i++) {
  13646. items[_i] = arguments[_i];
  13647. }
  13648. var result = oldPush.apply(array, items);
  13649. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  13650. var item = items_1[_a];
  13651. item._resyncLighSource(_this);
  13652. }
  13653. return result;
  13654. };
  13655. var oldSplice = array.splice;
  13656. array.splice = function (index, deleteCount) {
  13657. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13658. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  13659. var item = deleted_1[_i];
  13660. item._resyncLighSource(_this);
  13661. }
  13662. return deleted;
  13663. };
  13664. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  13665. var item = array_1[_i];
  13666. item._resyncLighSource(this);
  13667. }
  13668. };
  13669. Light.prototype._hookArrayForIncludedOnly = function (array) {
  13670. var _this = this;
  13671. var oldPush = array.push;
  13672. array.push = function () {
  13673. var items = [];
  13674. for (var _i = 0; _i < arguments.length; _i++) {
  13675. items[_i] = arguments[_i];
  13676. }
  13677. var result = oldPush.apply(array, items);
  13678. _this._resyncMeshes();
  13679. return result;
  13680. };
  13681. var oldSplice = array.splice;
  13682. array.splice = function (index, deleteCount) {
  13683. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13684. _this._resyncMeshes();
  13685. return deleted;
  13686. };
  13687. this._resyncMeshes();
  13688. };
  13689. Light.prototype._resyncMeshes = function () {
  13690. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13691. var mesh = _a[_i];
  13692. mesh._resyncLighSource(this);
  13693. }
  13694. };
  13695. Light.prototype._markMeshesAsLightDirty = function () {
  13696. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13697. var mesh = _a[_i];
  13698. if (mesh._lightSources.indexOf(this) !== -1) {
  13699. mesh._markSubMeshesAsLightDirty();
  13700. }
  13701. }
  13702. };
  13703. /**
  13704. * Recomputes the cached photometric scale if needed.
  13705. */
  13706. Light.prototype._computePhotometricScale = function () {
  13707. this._photometricScale = this._getPhotometricScale();
  13708. this.getScene().resetCachedMaterial();
  13709. };
  13710. /**
  13711. * Returns the Photometric Scale according to the light type and intensity mode.
  13712. */
  13713. Light.prototype._getPhotometricScale = function () {
  13714. var photometricScale = 0.0;
  13715. var lightTypeID = this.getTypeID();
  13716. //get photometric mode
  13717. var photometricMode = this.intensityMode;
  13718. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  13719. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  13720. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  13721. }
  13722. else {
  13723. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  13724. }
  13725. }
  13726. //compute photometric scale
  13727. switch (lightTypeID) {
  13728. case Light.LIGHTTYPEID_POINTLIGHT:
  13729. case Light.LIGHTTYPEID_SPOTLIGHT:
  13730. switch (photometricMode) {
  13731. case Light.INTENSITYMODE_LUMINOUSPOWER:
  13732. photometricScale = 1.0 / (4.0 * Math.PI);
  13733. break;
  13734. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  13735. photometricScale = 1.0;
  13736. break;
  13737. case Light.INTENSITYMODE_LUMINANCE:
  13738. photometricScale = this.radius * this.radius;
  13739. break;
  13740. }
  13741. break;
  13742. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  13743. switch (photometricMode) {
  13744. case Light.INTENSITYMODE_ILLUMINANCE:
  13745. photometricScale = 1.0;
  13746. break;
  13747. case Light.INTENSITYMODE_LUMINANCE:
  13748. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  13749. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  13750. var apexAngleRadians = this.radius;
  13751. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  13752. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  13753. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  13754. photometricScale = solidAngle;
  13755. break;
  13756. }
  13757. break;
  13758. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  13759. // No fall off in hemisperic light.
  13760. photometricScale = 1.0;
  13761. break;
  13762. }
  13763. return photometricScale;
  13764. };
  13765. Light.prototype._reorderLightsInScene = function () {
  13766. var scene = this.getScene();
  13767. if (this.renderPriority != 0) {
  13768. scene.requireLightSorting = true;
  13769. }
  13770. this.getScene().sortLightsByPriority();
  13771. };
  13772. return Light;
  13773. }(BABYLON.Node));
  13774. //lightmapMode Consts
  13775. Light._LIGHTMAP_DEFAULT = 0;
  13776. Light._LIGHTMAP_SPECULAR = 1;
  13777. Light._LIGHTMAP_SHADOWSONLY = 2;
  13778. // Intensity Mode Consts
  13779. Light._INTENSITYMODE_AUTOMATIC = 0;
  13780. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  13781. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  13782. Light._INTENSITYMODE_ILLUMINANCE = 3;
  13783. Light._INTENSITYMODE_LUMINANCE = 4;
  13784. // Light types ids const.
  13785. Light._LIGHTTYPEID_POINTLIGHT = 0;
  13786. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  13787. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  13788. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  13789. __decorate([
  13790. BABYLON.serializeAsColor3()
  13791. ], Light.prototype, "diffuse", void 0);
  13792. __decorate([
  13793. BABYLON.serializeAsColor3()
  13794. ], Light.prototype, "specular", void 0);
  13795. __decorate([
  13796. BABYLON.serialize()
  13797. ], Light.prototype, "intensity", void 0);
  13798. __decorate([
  13799. BABYLON.serialize()
  13800. ], Light.prototype, "range", void 0);
  13801. __decorate([
  13802. BABYLON.serialize()
  13803. ], Light.prototype, "intensityMode", null);
  13804. __decorate([
  13805. BABYLON.serialize()
  13806. ], Light.prototype, "radius", null);
  13807. __decorate([
  13808. BABYLON.serialize()
  13809. ], Light.prototype, "_renderPriority", void 0);
  13810. __decorate([
  13811. BABYLON.expandToProperty("_reorderLightsInScene")
  13812. ], Light.prototype, "renderPriority", void 0);
  13813. __decorate([
  13814. BABYLON.serialize()
  13815. ], Light.prototype, "shadowEnabled", void 0);
  13816. __decorate([
  13817. BABYLON.serialize("excludeWithLayerMask")
  13818. ], Light.prototype, "_excludeWithLayerMask", void 0);
  13819. __decorate([
  13820. BABYLON.serialize("includeOnlyWithLayerMask")
  13821. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  13822. __decorate([
  13823. BABYLON.serialize("lightmapMode")
  13824. ], Light.prototype, "_lightmapMode", void 0);
  13825. BABYLON.Light = Light;
  13826. })(BABYLON || (BABYLON = {}));
  13827. //# sourceMappingURL=babylon.light.js.map
  13828. var BABYLON;
  13829. (function (BABYLON) {
  13830. var Camera = (function (_super) {
  13831. __extends(Camera, _super);
  13832. function Camera(name, position, scene) {
  13833. var _this = _super.call(this, name, scene) || this;
  13834. _this.upVector = BABYLON.Vector3.Up();
  13835. _this.orthoLeft = null;
  13836. _this.orthoRight = null;
  13837. _this.orthoBottom = null;
  13838. _this.orthoTop = null;
  13839. _this.fov = 0.8;
  13840. _this.minZ = 1.0;
  13841. _this.maxZ = 10000.0;
  13842. _this.inertia = 0.9;
  13843. _this.mode = Camera.PERSPECTIVE_CAMERA;
  13844. _this.isIntermediate = false;
  13845. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  13846. _this.layerMask = 0x0FFFFFFF;
  13847. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  13848. // Camera rig members
  13849. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  13850. _this._rigCameras = new Array();
  13851. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  13852. // Cache
  13853. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  13854. _this._projectionMatrix = new BABYLON.Matrix();
  13855. _this._doNotComputeProjectionMatrix = false;
  13856. _this._postProcesses = new Array();
  13857. _this._transformMatrix = BABYLON.Matrix.Zero();
  13858. _this._activeMeshes = new BABYLON.SmartArray(256);
  13859. _this._globalPosition = BABYLON.Vector3.Zero();
  13860. _this._refreshFrustumPlanes = true;
  13861. _this.getScene().addCamera(_this);
  13862. if (!_this.getScene().activeCamera) {
  13863. _this.getScene().activeCamera = _this;
  13864. }
  13865. _this.position = position;
  13866. return _this;
  13867. }
  13868. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  13869. get: function () {
  13870. return Camera._PERSPECTIVE_CAMERA;
  13871. },
  13872. enumerable: true,
  13873. configurable: true
  13874. });
  13875. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  13876. get: function () {
  13877. return Camera._ORTHOGRAPHIC_CAMERA;
  13878. },
  13879. enumerable: true,
  13880. configurable: true
  13881. });
  13882. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  13883. get: function () {
  13884. return Camera._FOVMODE_VERTICAL_FIXED;
  13885. },
  13886. enumerable: true,
  13887. configurable: true
  13888. });
  13889. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  13890. get: function () {
  13891. return Camera._FOVMODE_HORIZONTAL_FIXED;
  13892. },
  13893. enumerable: true,
  13894. configurable: true
  13895. });
  13896. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  13897. get: function () {
  13898. return Camera._RIG_MODE_NONE;
  13899. },
  13900. enumerable: true,
  13901. configurable: true
  13902. });
  13903. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  13904. get: function () {
  13905. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  13906. },
  13907. enumerable: true,
  13908. configurable: true
  13909. });
  13910. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  13911. get: function () {
  13912. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  13913. },
  13914. enumerable: true,
  13915. configurable: true
  13916. });
  13917. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  13918. get: function () {
  13919. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13920. },
  13921. enumerable: true,
  13922. configurable: true
  13923. });
  13924. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  13925. get: function () {
  13926. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  13927. },
  13928. enumerable: true,
  13929. configurable: true
  13930. });
  13931. Object.defineProperty(Camera, "RIG_MODE_VR", {
  13932. get: function () {
  13933. return Camera._RIG_MODE_VR;
  13934. },
  13935. enumerable: true,
  13936. configurable: true
  13937. });
  13938. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  13939. get: function () {
  13940. return Camera._RIG_MODE_WEBVR;
  13941. },
  13942. enumerable: true,
  13943. configurable: true
  13944. });
  13945. Camera.prototype.getClassName = function () {
  13946. return "Camera";
  13947. };
  13948. /**
  13949. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13950. */
  13951. Camera.prototype.toString = function (fullDetails) {
  13952. var ret = "Name: " + this.name;
  13953. ret += ", type: " + this.getClassName();
  13954. if (this.animations) {
  13955. for (var i = 0; i < this.animations.length; i++) {
  13956. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13957. }
  13958. }
  13959. if (fullDetails) {
  13960. }
  13961. return ret;
  13962. };
  13963. Object.defineProperty(Camera.prototype, "globalPosition", {
  13964. get: function () {
  13965. return this._globalPosition;
  13966. },
  13967. enumerable: true,
  13968. configurable: true
  13969. });
  13970. Camera.prototype.getActiveMeshes = function () {
  13971. return this._activeMeshes;
  13972. };
  13973. Camera.prototype.isActiveMesh = function (mesh) {
  13974. return (this._activeMeshes.indexOf(mesh) !== -1);
  13975. };
  13976. //Cache
  13977. Camera.prototype._initCache = function () {
  13978. _super.prototype._initCache.call(this);
  13979. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13980. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13981. this._cache.mode = undefined;
  13982. this._cache.minZ = undefined;
  13983. this._cache.maxZ = undefined;
  13984. this._cache.fov = undefined;
  13985. this._cache.fovMode = undefined;
  13986. this._cache.aspectRatio = undefined;
  13987. this._cache.orthoLeft = undefined;
  13988. this._cache.orthoRight = undefined;
  13989. this._cache.orthoBottom = undefined;
  13990. this._cache.orthoTop = undefined;
  13991. this._cache.renderWidth = undefined;
  13992. this._cache.renderHeight = undefined;
  13993. };
  13994. Camera.prototype._updateCache = function (ignoreParentClass) {
  13995. if (!ignoreParentClass) {
  13996. _super.prototype._updateCache.call(this);
  13997. }
  13998. var engine = this.getEngine();
  13999. this._cache.position.copyFrom(this.position);
  14000. this._cache.upVector.copyFrom(this.upVector);
  14001. this._cache.mode = this.mode;
  14002. this._cache.minZ = this.minZ;
  14003. this._cache.maxZ = this.maxZ;
  14004. this._cache.fov = this.fov;
  14005. this._cache.fovMode = this.fovMode;
  14006. this._cache.aspectRatio = engine.getAspectRatio(this);
  14007. this._cache.orthoLeft = this.orthoLeft;
  14008. this._cache.orthoRight = this.orthoRight;
  14009. this._cache.orthoBottom = this.orthoBottom;
  14010. this._cache.orthoTop = this.orthoTop;
  14011. this._cache.renderWidth = engine.getRenderWidth();
  14012. this._cache.renderHeight = engine.getRenderHeight();
  14013. };
  14014. Camera.prototype._updateFromScene = function () {
  14015. this.updateCache();
  14016. this.update();
  14017. };
  14018. // Synchronized
  14019. Camera.prototype._isSynchronized = function () {
  14020. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  14021. };
  14022. Camera.prototype._isSynchronizedViewMatrix = function () {
  14023. if (!_super.prototype._isSynchronized.call(this))
  14024. return false;
  14025. return this._cache.position.equals(this.position)
  14026. && this._cache.upVector.equals(this.upVector)
  14027. && this.isSynchronizedWithParent();
  14028. };
  14029. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  14030. var check = this._cache.mode === this.mode
  14031. && this._cache.minZ === this.minZ
  14032. && this._cache.maxZ === this.maxZ;
  14033. if (!check) {
  14034. return false;
  14035. }
  14036. var engine = this.getEngine();
  14037. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14038. check = this._cache.fov === this.fov
  14039. && this._cache.fovMode === this.fovMode
  14040. && this._cache.aspectRatio === engine.getAspectRatio(this);
  14041. }
  14042. else {
  14043. check = this._cache.orthoLeft === this.orthoLeft
  14044. && this._cache.orthoRight === this.orthoRight
  14045. && this._cache.orthoBottom === this.orthoBottom
  14046. && this._cache.orthoTop === this.orthoTop
  14047. && this._cache.renderWidth === engine.getRenderWidth()
  14048. && this._cache.renderHeight === engine.getRenderHeight();
  14049. }
  14050. return check;
  14051. };
  14052. // Controls
  14053. Camera.prototype.attachControl = function (element, noPreventDefault) {
  14054. };
  14055. Camera.prototype.detachControl = function (element) {
  14056. };
  14057. Camera.prototype.update = function () {
  14058. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14059. this._updateRigCameras();
  14060. }
  14061. this._checkInputs();
  14062. };
  14063. Camera.prototype._checkInputs = function () {
  14064. };
  14065. Object.defineProperty(Camera.prototype, "rigCameras", {
  14066. get: function () {
  14067. return this._rigCameras;
  14068. },
  14069. enumerable: true,
  14070. configurable: true
  14071. });
  14072. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  14073. get: function () {
  14074. return this._rigPostProcess;
  14075. },
  14076. enumerable: true,
  14077. configurable: true
  14078. });
  14079. Camera.prototype._cascadePostProcessesToRigCams = function () {
  14080. // invalidate framebuffer
  14081. if (this._postProcesses.length > 0) {
  14082. this._postProcesses[0].markTextureDirty();
  14083. }
  14084. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  14085. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  14086. var cam = this._rigCameras[i];
  14087. var rigPostProcess = cam._rigPostProcess;
  14088. // for VR rig, there does not have to be a post process
  14089. if (rigPostProcess) {
  14090. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  14091. if (isPass) {
  14092. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  14093. cam.isIntermediate = this._postProcesses.length === 0;
  14094. }
  14095. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  14096. rigPostProcess.markTextureDirty();
  14097. }
  14098. else {
  14099. cam._postProcesses = this._postProcesses.slice(0);
  14100. }
  14101. }
  14102. };
  14103. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  14104. if (insertAt === void 0) { insertAt = null; }
  14105. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  14106. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  14107. return 0;
  14108. }
  14109. if (insertAt == null || insertAt < 0) {
  14110. this._postProcesses.push(postProcess);
  14111. }
  14112. else {
  14113. this._postProcesses.splice(insertAt, 0, postProcess);
  14114. }
  14115. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14116. return this._postProcesses.indexOf(postProcess);
  14117. };
  14118. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  14119. if (atIndices === void 0) { atIndices = null; }
  14120. var result = [];
  14121. var i;
  14122. var index;
  14123. if (!atIndices) {
  14124. var idx = this._postProcesses.indexOf(postProcess);
  14125. if (idx !== -1) {
  14126. this._postProcesses.splice(idx, 1);
  14127. }
  14128. }
  14129. else {
  14130. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  14131. // iterate descending, so can just splice as we go
  14132. for (i = atIndices.length - 1; i >= 0; i--) {
  14133. if (this._postProcesses[atIndices[i]] !== postProcess) {
  14134. result.push(i);
  14135. continue;
  14136. }
  14137. index = atIndices[i];
  14138. this._postProcesses.splice(index, 1);
  14139. }
  14140. }
  14141. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14142. return result;
  14143. };
  14144. Camera.prototype.getWorldMatrix = function () {
  14145. if (!this._worldMatrix) {
  14146. this._worldMatrix = BABYLON.Matrix.Identity();
  14147. }
  14148. var viewMatrix = this.getViewMatrix();
  14149. viewMatrix.invertToRef(this._worldMatrix);
  14150. return this._worldMatrix;
  14151. };
  14152. Camera.prototype._getViewMatrix = function () {
  14153. return BABYLON.Matrix.Identity();
  14154. };
  14155. Camera.prototype.getViewMatrix = function (force) {
  14156. this._computedViewMatrix = this._computeViewMatrix(force);
  14157. if (!force && this._isSynchronizedViewMatrix()) {
  14158. return this._computedViewMatrix;
  14159. }
  14160. this._refreshFrustumPlanes = true;
  14161. if (!this.parent || !this.parent.getWorldMatrix) {
  14162. this._globalPosition.copyFrom(this.position);
  14163. }
  14164. else {
  14165. if (!this._worldMatrix) {
  14166. this._worldMatrix = BABYLON.Matrix.Identity();
  14167. }
  14168. this._computedViewMatrix.invertToRef(this._worldMatrix);
  14169. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  14170. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  14171. this._computedViewMatrix.invert();
  14172. this._markSyncedWithParent();
  14173. }
  14174. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  14175. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  14176. }
  14177. this._currentRenderId = this.getScene().getRenderId();
  14178. return this._computedViewMatrix;
  14179. };
  14180. Camera.prototype._computeViewMatrix = function (force) {
  14181. if (!force && this._isSynchronizedViewMatrix()) {
  14182. return this._computedViewMatrix;
  14183. }
  14184. this._computedViewMatrix = this._getViewMatrix();
  14185. this._currentRenderId = this.getScene().getRenderId();
  14186. return this._computedViewMatrix;
  14187. };
  14188. Camera.prototype.freezeProjectionMatrix = function (projection) {
  14189. this._doNotComputeProjectionMatrix = true;
  14190. if (projection !== undefined) {
  14191. this._projectionMatrix = projection;
  14192. }
  14193. };
  14194. ;
  14195. Camera.prototype.unfreezeProjectionMatrix = function () {
  14196. this._doNotComputeProjectionMatrix = false;
  14197. };
  14198. ;
  14199. Camera.prototype.getProjectionMatrix = function (force) {
  14200. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  14201. return this._projectionMatrix;
  14202. }
  14203. this._refreshFrustumPlanes = true;
  14204. var engine = this.getEngine();
  14205. var scene = this.getScene();
  14206. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14207. if (this.minZ <= 0) {
  14208. this.minZ = 0.1;
  14209. }
  14210. if (scene.useRightHandedSystem) {
  14211. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14212. }
  14213. else {
  14214. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14215. }
  14216. return this._projectionMatrix;
  14217. }
  14218. var halfWidth = engine.getRenderWidth() / 2.0;
  14219. var halfHeight = engine.getRenderHeight() / 2.0;
  14220. if (scene.useRightHandedSystem) {
  14221. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14222. }
  14223. else {
  14224. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14225. }
  14226. return this._projectionMatrix;
  14227. };
  14228. Camera.prototype.getTranformationMatrix = function () {
  14229. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14230. return this._transformMatrix;
  14231. };
  14232. Camera.prototype.updateFrustumPlanes = function () {
  14233. if (!this._refreshFrustumPlanes) {
  14234. return;
  14235. }
  14236. this.getTranformationMatrix();
  14237. if (!this._frustumPlanes) {
  14238. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  14239. }
  14240. else {
  14241. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  14242. }
  14243. this._refreshFrustumPlanes = false;
  14244. };
  14245. Camera.prototype.isInFrustum = function (target) {
  14246. this.updateFrustumPlanes();
  14247. return target.isInFrustum(this._frustumPlanes);
  14248. };
  14249. Camera.prototype.isCompletelyInFrustum = function (target) {
  14250. this.updateFrustumPlanes();
  14251. return target.isCompletelyInFrustum(this._frustumPlanes);
  14252. };
  14253. Camera.prototype.getForwardRay = function (length, transform, origin) {
  14254. if (length === void 0) { length = 100; }
  14255. if (!transform) {
  14256. transform = this.getWorldMatrix();
  14257. }
  14258. if (!origin) {
  14259. origin = this.position;
  14260. }
  14261. var forward = new BABYLON.Vector3(0, 0, 1);
  14262. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  14263. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  14264. return new BABYLON.Ray(origin, direction, length);
  14265. };
  14266. Camera.prototype.dispose = function () {
  14267. // Animations
  14268. this.getScene().stopAnimation(this);
  14269. // Remove from scene
  14270. this.getScene().removeCamera(this);
  14271. while (this._rigCameras.length > 0) {
  14272. this._rigCameras.pop().dispose();
  14273. }
  14274. // Postprocesses
  14275. var i = this._postProcesses.length;
  14276. while (--i >= 0) {
  14277. this._postProcesses[i].dispose(this);
  14278. }
  14279. _super.prototype.dispose.call(this);
  14280. };
  14281. Object.defineProperty(Camera.prototype, "leftCamera", {
  14282. // ---- Camera rigs section ----
  14283. get: function () {
  14284. if (this._rigCameras.length < 1) {
  14285. return undefined;
  14286. }
  14287. return this._rigCameras[0];
  14288. },
  14289. enumerable: true,
  14290. configurable: true
  14291. });
  14292. Object.defineProperty(Camera.prototype, "rightCamera", {
  14293. get: function () {
  14294. if (this._rigCameras.length < 2) {
  14295. return undefined;
  14296. }
  14297. return this._rigCameras[1];
  14298. },
  14299. enumerable: true,
  14300. configurable: true
  14301. });
  14302. Camera.prototype.getLeftTarget = function () {
  14303. if (this._rigCameras.length < 1) {
  14304. return undefined;
  14305. }
  14306. return this._rigCameras[0].getTarget();
  14307. };
  14308. Camera.prototype.getRightTarget = function () {
  14309. if (this._rigCameras.length < 2) {
  14310. return undefined;
  14311. }
  14312. return this._rigCameras[1].getTarget();
  14313. };
  14314. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  14315. while (this._rigCameras.length > 0) {
  14316. this._rigCameras.pop().dispose();
  14317. }
  14318. this.cameraRigMode = mode;
  14319. this._cameraRigParams = {};
  14320. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  14321. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  14322. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  14323. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  14324. // create the rig cameras, unless none
  14325. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14326. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  14327. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  14328. }
  14329. switch (this.cameraRigMode) {
  14330. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14331. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14332. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  14333. break;
  14334. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14335. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14336. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14337. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14338. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14339. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  14340. break;
  14341. case Camera.RIG_MODE_VR:
  14342. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  14343. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  14344. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14345. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14346. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  14347. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  14348. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  14349. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  14350. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14351. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14352. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  14353. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  14354. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  14355. if (metrics.compensateDistortion) {
  14356. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  14357. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  14358. }
  14359. break;
  14360. case Camera.RIG_MODE_WEBVR:
  14361. if (rigParams.vrDisplay) {
  14362. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  14363. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  14364. //Left eye
  14365. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14366. this._rigCameras[0].setCameraRigParameter("left", true);
  14367. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  14368. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  14369. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  14370. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14371. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14372. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14373. this._rigCameras[0].parent = this;
  14374. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  14375. //Right eye
  14376. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14377. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  14378. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  14379. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  14380. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14381. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14382. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14383. this._rigCameras[1].parent = this;
  14384. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  14385. }
  14386. break;
  14387. }
  14388. this._cascadePostProcessesToRigCams();
  14389. this.
  14390. update();
  14391. };
  14392. Camera.prototype._getVRProjectionMatrix = function () {
  14393. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  14394. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  14395. return this._projectionMatrix;
  14396. };
  14397. Camera.prototype._updateCameraRotationMatrix = function () {
  14398. //Here for WebVR
  14399. };
  14400. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  14401. //Here for WebVR
  14402. };
  14403. /**
  14404. * This function MUST be overwritten by the different WebVR cameras available.
  14405. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14406. */
  14407. Camera.prototype._getWebVRProjectionMatrix = function () {
  14408. return BABYLON.Matrix.Identity();
  14409. };
  14410. /**
  14411. * This function MUST be overwritten by the different WebVR cameras available.
  14412. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14413. */
  14414. Camera.prototype._getWebVRViewMatrix = function () {
  14415. return BABYLON.Matrix.Identity();
  14416. };
  14417. Camera.prototype.setCameraRigParameter = function (name, value) {
  14418. if (!this._cameraRigParams) {
  14419. this._cameraRigParams = {};
  14420. }
  14421. this._cameraRigParams[name] = value;
  14422. //provisionnally:
  14423. if (name === "interaxialDistance") {
  14424. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  14425. }
  14426. };
  14427. /**
  14428. * needs to be overridden by children so sub has required properties to be copied
  14429. */
  14430. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  14431. return null;
  14432. };
  14433. /**
  14434. * May need to be overridden by children
  14435. */
  14436. Camera.prototype._updateRigCameras = function () {
  14437. for (var i = 0; i < this._rigCameras.length; i++) {
  14438. this._rigCameras[i].minZ = this.minZ;
  14439. this._rigCameras[i].maxZ = this.maxZ;
  14440. this._rigCameras[i].fov = this.fov;
  14441. }
  14442. // only update viewport when ANAGLYPH
  14443. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  14444. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  14445. }
  14446. };
  14447. Camera.prototype._setupInputs = function () {
  14448. };
  14449. Camera.prototype.serialize = function () {
  14450. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14451. // Type
  14452. serializationObject.type = this.getClassName();
  14453. // Parent
  14454. if (this.parent) {
  14455. serializationObject.parentId = this.parent.id;
  14456. }
  14457. if (this.inputs) {
  14458. this.inputs.serialize(serializationObject);
  14459. }
  14460. // Animations
  14461. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14462. serializationObject.ranges = this.serializeAnimationRanges();
  14463. return serializationObject;
  14464. };
  14465. Camera.prototype.clone = function (name) {
  14466. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  14467. };
  14468. Camera.prototype.getDirection = function (localAxis) {
  14469. var result = BABYLON.Vector3.Zero();
  14470. this.getDirectionToRef(localAxis, result);
  14471. return result;
  14472. };
  14473. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  14474. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14475. };
  14476. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  14477. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  14478. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  14479. switch (type) {
  14480. case "ArcRotateCamera":
  14481. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  14482. case "DeviceOrientationCamera":
  14483. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  14484. case "FollowCamera":
  14485. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  14486. case "ArcFollowCamera":
  14487. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  14488. case "GamepadCamera":
  14489. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14490. case "TouchCamera":
  14491. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  14492. case "VirtualJoysticksCamera":
  14493. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  14494. case "WebVRFreeCamera":
  14495. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14496. case "WebVRGamepadCamera":
  14497. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14498. case "VRDeviceOrientationFreeCamera":
  14499. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14500. case "VRDeviceOrientationGamepadCamera":
  14501. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14502. case "AnaglyphArcRotateCamera":
  14503. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14504. case "AnaglyphFreeCamera":
  14505. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14506. case "AnaglyphGamepadCamera":
  14507. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14508. case "AnaglyphUniversalCamera":
  14509. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14510. case "StereoscopicArcRotateCamera":
  14511. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14512. case "StereoscopicFreeCamera":
  14513. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14514. case "StereoscopicGamepadCamera":
  14515. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14516. case "StereoscopicUniversalCamera":
  14517. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14518. case "FreeCamera":
  14519. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14520. default:
  14521. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14522. }
  14523. };
  14524. Camera.Parse = function (parsedCamera, scene) {
  14525. var type = parsedCamera.type;
  14526. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  14527. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  14528. // Parent
  14529. if (parsedCamera.parentId) {
  14530. camera._waitingParentId = parsedCamera.parentId;
  14531. }
  14532. //If camera has an input manager, let it parse inputs settings
  14533. if (camera.inputs) {
  14534. camera.inputs.parse(parsedCamera);
  14535. camera._setupInputs();
  14536. }
  14537. // Target
  14538. if (parsedCamera.target) {
  14539. if (camera.setTarget) {
  14540. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  14541. }
  14542. }
  14543. // Apply 3d rig, when found
  14544. if (parsedCamera.cameraRigMode) {
  14545. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  14546. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  14547. }
  14548. // Animations
  14549. if (parsedCamera.animations) {
  14550. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  14551. var parsedAnimation = parsedCamera.animations[animationIndex];
  14552. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14553. }
  14554. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  14555. }
  14556. if (parsedCamera.autoAnimate) {
  14557. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  14558. }
  14559. return camera;
  14560. };
  14561. return Camera;
  14562. }(BABYLON.Node));
  14563. // Statics
  14564. Camera._PERSPECTIVE_CAMERA = 0;
  14565. Camera._ORTHOGRAPHIC_CAMERA = 1;
  14566. Camera._FOVMODE_VERTICAL_FIXED = 0;
  14567. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  14568. Camera._RIG_MODE_NONE = 0;
  14569. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  14570. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  14571. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  14572. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  14573. Camera._RIG_MODE_VR = 20;
  14574. Camera._RIG_MODE_WEBVR = 21;
  14575. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  14576. __decorate([
  14577. BABYLON.serializeAsVector3()
  14578. ], Camera.prototype, "position", void 0);
  14579. __decorate([
  14580. BABYLON.serializeAsVector3()
  14581. ], Camera.prototype, "upVector", void 0);
  14582. __decorate([
  14583. BABYLON.serialize()
  14584. ], Camera.prototype, "orthoLeft", void 0);
  14585. __decorate([
  14586. BABYLON.serialize()
  14587. ], Camera.prototype, "orthoRight", void 0);
  14588. __decorate([
  14589. BABYLON.serialize()
  14590. ], Camera.prototype, "orthoBottom", void 0);
  14591. __decorate([
  14592. BABYLON.serialize()
  14593. ], Camera.prototype, "orthoTop", void 0);
  14594. __decorate([
  14595. BABYLON.serialize()
  14596. ], Camera.prototype, "fov", void 0);
  14597. __decorate([
  14598. BABYLON.serialize()
  14599. ], Camera.prototype, "minZ", void 0);
  14600. __decorate([
  14601. BABYLON.serialize()
  14602. ], Camera.prototype, "maxZ", void 0);
  14603. __decorate([
  14604. BABYLON.serialize()
  14605. ], Camera.prototype, "inertia", void 0);
  14606. __decorate([
  14607. BABYLON.serialize()
  14608. ], Camera.prototype, "mode", void 0);
  14609. __decorate([
  14610. BABYLON.serialize()
  14611. ], Camera.prototype, "layerMask", void 0);
  14612. __decorate([
  14613. BABYLON.serialize()
  14614. ], Camera.prototype, "fovMode", void 0);
  14615. __decorate([
  14616. BABYLON.serialize()
  14617. ], Camera.prototype, "cameraRigMode", void 0);
  14618. __decorate([
  14619. BABYLON.serialize()
  14620. ], Camera.prototype, "interaxialDistance", void 0);
  14621. __decorate([
  14622. BABYLON.serialize()
  14623. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  14624. BABYLON.Camera = Camera;
  14625. })(BABYLON || (BABYLON = {}));
  14626. //# sourceMappingURL=babylon.camera.js.map
  14627. var BABYLON;
  14628. (function (BABYLON) {
  14629. var RenderingManager = (function () {
  14630. function RenderingManager(scene) {
  14631. this._renderingGroups = new Array();
  14632. this._autoClearDepthStencil = {};
  14633. this._customOpaqueSortCompareFn = {};
  14634. this._customAlphaTestSortCompareFn = {};
  14635. this._customTransparentSortCompareFn = {};
  14636. this._renderinGroupInfo = null;
  14637. this._scene = scene;
  14638. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  14639. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  14640. }
  14641. }
  14642. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  14643. if (depth === void 0) { depth = true; }
  14644. if (stencil === void 0) { stencil = true; }
  14645. if (this._depthStencilBufferAlreadyCleaned) {
  14646. return;
  14647. }
  14648. this._scene.getEngine().clear(null, false, depth, stencil);
  14649. this._depthStencilBufferAlreadyCleaned = true;
  14650. };
  14651. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  14652. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  14653. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  14654. var info = null;
  14655. if (observable) {
  14656. if (!this._renderinGroupInfo) {
  14657. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  14658. }
  14659. info = this._renderinGroupInfo;
  14660. info.scene = this._scene;
  14661. info.camera = this._scene.activeCamera;
  14662. }
  14663. // Dispatch sprites
  14664. if (renderSprites) {
  14665. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  14666. var manager = this._scene.spriteManagers[index];
  14667. this.dispatchSprites(manager);
  14668. }
  14669. }
  14670. // Render
  14671. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14672. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  14673. var renderingGroup = this._renderingGroups[index];
  14674. if (!renderingGroup && !observable)
  14675. continue;
  14676. this._currentIndex = index;
  14677. var renderingGroupMask = 0;
  14678. // Fire PRECLEAR stage
  14679. if (observable) {
  14680. renderingGroupMask = Math.pow(2, index);
  14681. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  14682. info.renderingGroupId = index;
  14683. observable.notifyObservers(info, renderingGroupMask);
  14684. }
  14685. // Clear depth/stencil if needed
  14686. if (RenderingManager.AUTOCLEAR) {
  14687. var autoClear = this._autoClearDepthStencil[index];
  14688. if (autoClear && autoClear.autoClear) {
  14689. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  14690. }
  14691. }
  14692. if (observable) {
  14693. // Fire PREOPAQUE stage
  14694. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  14695. observable.notifyObservers(info, renderingGroupMask);
  14696. // Fire PRETRANSPARENT stage
  14697. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  14698. observable.notifyObservers(info, renderingGroupMask);
  14699. }
  14700. if (renderingGroup)
  14701. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  14702. // Fire POSTTRANSPARENT stage
  14703. if (observable) {
  14704. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  14705. observable.notifyObservers(info, renderingGroupMask);
  14706. }
  14707. }
  14708. };
  14709. RenderingManager.prototype.reset = function () {
  14710. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14711. var renderingGroup = this._renderingGroups[index];
  14712. if (renderingGroup) {
  14713. renderingGroup.prepare();
  14714. }
  14715. }
  14716. };
  14717. RenderingManager.prototype.dispose = function () {
  14718. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14719. var renderingGroup = this._renderingGroups[index];
  14720. if (renderingGroup) {
  14721. renderingGroup.dispose();
  14722. }
  14723. }
  14724. this._renderingGroups.length = 0;
  14725. };
  14726. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  14727. if (!this._renderingGroups[renderingGroupId]) {
  14728. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  14729. }
  14730. };
  14731. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  14732. var renderingGroupId = spriteManager.renderingGroupId || 0;
  14733. this._prepareRenderingGroup(renderingGroupId);
  14734. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  14735. };
  14736. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  14737. var renderingGroupId = particleSystem.renderingGroupId || 0;
  14738. this._prepareRenderingGroup(renderingGroupId);
  14739. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  14740. };
  14741. RenderingManager.prototype.dispatch = function (subMesh) {
  14742. var mesh = subMesh.getMesh();
  14743. var renderingGroupId = mesh.renderingGroupId || 0;
  14744. this._prepareRenderingGroup(renderingGroupId);
  14745. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  14746. };
  14747. /**
  14748. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  14749. * This allowed control for front to back rendering or reversly depending of the special needs.
  14750. *
  14751. * @param renderingGroupId The rendering group id corresponding to its index
  14752. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  14753. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  14754. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  14755. */
  14756. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14757. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14758. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14759. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14760. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  14761. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  14762. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  14763. if (this._renderingGroups[renderingGroupId]) {
  14764. var group = this._renderingGroups[renderingGroupId];
  14765. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  14766. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  14767. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  14768. }
  14769. };
  14770. /**
  14771. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  14772. *
  14773. * @param renderingGroupId The rendering group id corresponding to its index
  14774. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  14775. * @param depth Automatically clears depth between groups if true and autoClear is true.
  14776. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  14777. */
  14778. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  14779. if (depth === void 0) { depth = true; }
  14780. if (stencil === void 0) { stencil = true; }
  14781. this._autoClearDepthStencil[renderingGroupId] = {
  14782. autoClear: autoClearDepthStencil,
  14783. depth: depth,
  14784. stencil: stencil
  14785. };
  14786. };
  14787. return RenderingManager;
  14788. }());
  14789. /**
  14790. * The max id used for rendering groups (not included)
  14791. */
  14792. RenderingManager.MAX_RENDERINGGROUPS = 4;
  14793. /**
  14794. * The min id used for rendering groups (included)
  14795. */
  14796. RenderingManager.MIN_RENDERINGGROUPS = 0;
  14797. /**
  14798. * Used to globally prevent autoclearing scenes.
  14799. */
  14800. RenderingManager.AUTOCLEAR = true;
  14801. BABYLON.RenderingManager = RenderingManager;
  14802. })(BABYLON || (BABYLON = {}));
  14803. //# sourceMappingURL=babylon.renderingManager.js.map
  14804. var BABYLON;
  14805. (function (BABYLON) {
  14806. var RenderingGroup = (function () {
  14807. /**
  14808. * Creates a new rendering group.
  14809. * @param index The rendering group index
  14810. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  14811. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  14812. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  14813. */
  14814. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14815. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14816. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14817. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14818. this.index = index;
  14819. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  14820. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  14821. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  14822. this._particleSystems = new BABYLON.SmartArray(256);
  14823. this._spriteManagers = new BABYLON.SmartArray(256);
  14824. this._edgesRenderers = new BABYLON.SmartArray(16);
  14825. this._scene = scene;
  14826. this.opaqueSortCompareFn = opaqueSortCompareFn;
  14827. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  14828. this.transparentSortCompareFn = transparentSortCompareFn;
  14829. }
  14830. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  14831. /**
  14832. * Set the opaque sort comparison function.
  14833. * If null the sub meshes will be render in the order they were created
  14834. */
  14835. set: function (value) {
  14836. this._opaqueSortCompareFn = value;
  14837. if (value) {
  14838. this._renderOpaque = this.renderOpaqueSorted;
  14839. }
  14840. else {
  14841. this._renderOpaque = RenderingGroup.renderUnsorted;
  14842. }
  14843. },
  14844. enumerable: true,
  14845. configurable: true
  14846. });
  14847. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  14848. /**
  14849. * Set the alpha test sort comparison function.
  14850. * If null the sub meshes will be render in the order they were created
  14851. */
  14852. set: function (value) {
  14853. this._alphaTestSortCompareFn = value;
  14854. if (value) {
  14855. this._renderAlphaTest = this.renderAlphaTestSorted;
  14856. }
  14857. else {
  14858. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  14859. }
  14860. },
  14861. enumerable: true,
  14862. configurable: true
  14863. });
  14864. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  14865. /**
  14866. * Set the transparent sort comparison function.
  14867. * If null the sub meshes will be render in the order they were created
  14868. */
  14869. set: function (value) {
  14870. if (value) {
  14871. this._transparentSortCompareFn = value;
  14872. }
  14873. else {
  14874. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  14875. }
  14876. this._renderTransparent = this.renderTransparentSorted;
  14877. },
  14878. enumerable: true,
  14879. configurable: true
  14880. });
  14881. /**
  14882. * Render all the sub meshes contained in the group.
  14883. * @param customRenderFunction Used to override the default render behaviour of the group.
  14884. * @returns true if rendered some submeshes.
  14885. */
  14886. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  14887. if (customRenderFunction) {
  14888. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  14889. return;
  14890. }
  14891. var engine = this._scene.getEngine();
  14892. // Opaque
  14893. if (this._opaqueSubMeshes.length !== 0) {
  14894. this._renderOpaque(this._opaqueSubMeshes);
  14895. }
  14896. // Alpha test
  14897. if (this._alphaTestSubMeshes.length !== 0) {
  14898. engine.setAlphaTesting(true);
  14899. this._renderAlphaTest(this._alphaTestSubMeshes);
  14900. engine.setAlphaTesting(false);
  14901. }
  14902. var stencilState = engine.getStencilBuffer();
  14903. engine.setStencilBuffer(false);
  14904. // Sprites
  14905. if (renderSprites) {
  14906. this._renderSprites();
  14907. }
  14908. // Particles
  14909. if (renderParticles) {
  14910. this._renderParticles(activeMeshes);
  14911. }
  14912. if (this.onBeforeTransparentRendering) {
  14913. this.onBeforeTransparentRendering();
  14914. }
  14915. // Transparent
  14916. if (this._transparentSubMeshes.length !== 0) {
  14917. this._renderTransparent(this._transparentSubMeshes);
  14918. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14919. }
  14920. engine.setStencilBuffer(stencilState);
  14921. // Edges
  14922. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  14923. this._edgesRenderers.data[edgesRendererIndex].render();
  14924. }
  14925. };
  14926. /**
  14927. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  14928. * @param subMeshes The submeshes to render
  14929. */
  14930. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  14931. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  14932. };
  14933. /**
  14934. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  14935. * @param subMeshes The submeshes to render
  14936. */
  14937. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  14938. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  14939. };
  14940. /**
  14941. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  14942. * @param subMeshes The submeshes to render
  14943. */
  14944. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  14945. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  14946. };
  14947. /**
  14948. * Renders the submeshes in a specified order.
  14949. * @param subMeshes The submeshes to sort before render
  14950. * @param sortCompareFn The comparison function use to sort
  14951. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  14952. * @param transparent Specifies to activate blending if true
  14953. */
  14954. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  14955. var subIndex = 0;
  14956. var subMesh;
  14957. for (; subIndex < subMeshes.length; subIndex++) {
  14958. subMesh = subMeshes.data[subIndex];
  14959. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  14960. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  14961. }
  14962. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  14963. sortedArray.sort(sortCompareFn);
  14964. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  14965. subMesh = sortedArray[subIndex];
  14966. subMesh.render(transparent);
  14967. }
  14968. };
  14969. /**
  14970. * Renders the submeshes in the order they were dispatched (no sort applied).
  14971. * @param subMeshes The submeshes to render
  14972. */
  14973. RenderingGroup.renderUnsorted = function (subMeshes) {
  14974. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  14975. var submesh = subMeshes.data[subIndex];
  14976. submesh.render(false);
  14977. }
  14978. };
  14979. /**
  14980. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14981. * are rendered back to front if in the same alpha index.
  14982. *
  14983. * @param a The first submesh
  14984. * @param b The second submesh
  14985. * @returns The result of the comparison
  14986. */
  14987. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  14988. // Alpha index first
  14989. if (a._alphaIndex > b._alphaIndex) {
  14990. return 1;
  14991. }
  14992. if (a._alphaIndex < b._alphaIndex) {
  14993. return -1;
  14994. }
  14995. // Then distance to camera
  14996. return RenderingGroup.backToFrontSortCompare(a, b);
  14997. };
  14998. /**
  14999. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15000. * are rendered back to front.
  15001. *
  15002. * @param a The first submesh
  15003. * @param b The second submesh
  15004. * @returns The result of the comparison
  15005. */
  15006. RenderingGroup.backToFrontSortCompare = function (a, b) {
  15007. // Then distance to camera
  15008. if (a._distanceToCamera < b._distanceToCamera) {
  15009. return 1;
  15010. }
  15011. if (a._distanceToCamera > b._distanceToCamera) {
  15012. return -1;
  15013. }
  15014. return 0;
  15015. };
  15016. /**
  15017. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15018. * are rendered front to back (prevent overdraw).
  15019. *
  15020. * @param a The first submesh
  15021. * @param b The second submesh
  15022. * @returns The result of the comparison
  15023. */
  15024. RenderingGroup.frontToBackSortCompare = function (a, b) {
  15025. // Then distance to camera
  15026. if (a._distanceToCamera < b._distanceToCamera) {
  15027. return -1;
  15028. }
  15029. if (a._distanceToCamera > b._distanceToCamera) {
  15030. return 1;
  15031. }
  15032. return 0;
  15033. };
  15034. /**
  15035. * Resets the different lists of submeshes to prepare a new frame.
  15036. */
  15037. RenderingGroup.prototype.prepare = function () {
  15038. this._opaqueSubMeshes.reset();
  15039. this._transparentSubMeshes.reset();
  15040. this._alphaTestSubMeshes.reset();
  15041. this._particleSystems.reset();
  15042. this._spriteManagers.reset();
  15043. this._edgesRenderers.reset();
  15044. };
  15045. RenderingGroup.prototype.dispose = function () {
  15046. this._opaqueSubMeshes.dispose();
  15047. this._transparentSubMeshes.dispose();
  15048. this._alphaTestSubMeshes.dispose();
  15049. this._particleSystems.dispose();
  15050. this._spriteManagers.dispose();
  15051. this._edgesRenderers.dispose();
  15052. };
  15053. /**
  15054. * Inserts the submesh in its correct queue depending on its material.
  15055. * @param subMesh The submesh to dispatch
  15056. */
  15057. RenderingGroup.prototype.dispatch = function (subMesh) {
  15058. var material = subMesh.getMaterial();
  15059. var mesh = subMesh.getMesh();
  15060. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  15061. this._transparentSubMeshes.push(subMesh);
  15062. }
  15063. else if (material.needAlphaTesting()) {
  15064. this._alphaTestSubMeshes.push(subMesh);
  15065. }
  15066. else {
  15067. this._opaqueSubMeshes.push(subMesh); // Opaque
  15068. }
  15069. if (mesh._edgesRenderer) {
  15070. this._edgesRenderers.push(mesh._edgesRenderer);
  15071. }
  15072. };
  15073. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  15074. this._spriteManagers.push(spriteManager);
  15075. };
  15076. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  15077. this._particleSystems.push(particleSystem);
  15078. };
  15079. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  15080. if (this._particleSystems.length === 0) {
  15081. return;
  15082. }
  15083. // Particles
  15084. var activeCamera = this._scene.activeCamera;
  15085. this._scene._particlesDuration.beginMonitoring();
  15086. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15087. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  15088. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  15089. continue;
  15090. }
  15091. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  15092. this._scene._activeParticles.addCount(particleSystem.render(), false);
  15093. }
  15094. }
  15095. this._scene._particlesDuration.endMonitoring(false);
  15096. };
  15097. RenderingGroup.prototype._renderSprites = function () {
  15098. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  15099. return;
  15100. }
  15101. // Sprites
  15102. var activeCamera = this._scene.activeCamera;
  15103. this._scene._spritesDuration.beginMonitoring();
  15104. for (var id = 0; id < this._spriteManagers.length; id++) {
  15105. var spriteManager = this._spriteManagers.data[id];
  15106. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  15107. spriteManager.render();
  15108. }
  15109. }
  15110. this._scene._spritesDuration.endMonitoring(false);
  15111. };
  15112. return RenderingGroup;
  15113. }());
  15114. BABYLON.RenderingGroup = RenderingGroup;
  15115. })(BABYLON || (BABYLON = {}));
  15116. //# sourceMappingURL=babylon.renderingGroup.js.map
  15117. var BABYLON;
  15118. (function (BABYLON) {
  15119. var ClickInfo = (function () {
  15120. function ClickInfo() {
  15121. this._singleClick = false;
  15122. this._doubleClick = false;
  15123. this._hasSwiped = false;
  15124. this._ignore = false;
  15125. }
  15126. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  15127. get: function () {
  15128. return this._singleClick;
  15129. },
  15130. set: function (b) {
  15131. this._singleClick = b;
  15132. },
  15133. enumerable: true,
  15134. configurable: true
  15135. });
  15136. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  15137. get: function () {
  15138. return this._doubleClick;
  15139. },
  15140. set: function (b) {
  15141. this._doubleClick = b;
  15142. },
  15143. enumerable: true,
  15144. configurable: true
  15145. });
  15146. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  15147. get: function () {
  15148. return this._hasSwiped;
  15149. },
  15150. set: function (b) {
  15151. this._hasSwiped = b;
  15152. },
  15153. enumerable: true,
  15154. configurable: true
  15155. });
  15156. Object.defineProperty(ClickInfo.prototype, "ignore", {
  15157. get: function () {
  15158. return this._ignore;
  15159. },
  15160. set: function (b) {
  15161. this._ignore = b;
  15162. },
  15163. enumerable: true,
  15164. configurable: true
  15165. });
  15166. return ClickInfo;
  15167. }());
  15168. var PointerEventTypes = (function () {
  15169. function PointerEventTypes() {
  15170. }
  15171. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  15172. get: function () {
  15173. return PointerEventTypes._POINTERDOWN;
  15174. },
  15175. enumerable: true,
  15176. configurable: true
  15177. });
  15178. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  15179. get: function () {
  15180. return PointerEventTypes._POINTERUP;
  15181. },
  15182. enumerable: true,
  15183. configurable: true
  15184. });
  15185. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  15186. get: function () {
  15187. return PointerEventTypes._POINTERMOVE;
  15188. },
  15189. enumerable: true,
  15190. configurable: true
  15191. });
  15192. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  15193. get: function () {
  15194. return PointerEventTypes._POINTERWHEEL;
  15195. },
  15196. enumerable: true,
  15197. configurable: true
  15198. });
  15199. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  15200. get: function () {
  15201. return PointerEventTypes._POINTERPICK;
  15202. },
  15203. enumerable: true,
  15204. configurable: true
  15205. });
  15206. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  15207. get: function () {
  15208. return PointerEventTypes._POINTERTAP;
  15209. },
  15210. enumerable: true,
  15211. configurable: true
  15212. });
  15213. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  15214. get: function () {
  15215. return PointerEventTypes._POINTERDOUBLETAP;
  15216. },
  15217. enumerable: true,
  15218. configurable: true
  15219. });
  15220. return PointerEventTypes;
  15221. }());
  15222. PointerEventTypes._POINTERDOWN = 0x01;
  15223. PointerEventTypes._POINTERUP = 0x02;
  15224. PointerEventTypes._POINTERMOVE = 0x04;
  15225. PointerEventTypes._POINTERWHEEL = 0x08;
  15226. PointerEventTypes._POINTERPICK = 0x10;
  15227. PointerEventTypes._POINTERTAP = 0x20;
  15228. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  15229. BABYLON.PointerEventTypes = PointerEventTypes;
  15230. var PointerInfoBase = (function () {
  15231. function PointerInfoBase(type, event) {
  15232. this.type = type;
  15233. this.event = event;
  15234. }
  15235. return PointerInfoBase;
  15236. }());
  15237. BABYLON.PointerInfoBase = PointerInfoBase;
  15238. /**
  15239. * This class is used to store pointer related info for the onPrePointerObservable event.
  15240. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  15241. */
  15242. var PointerInfoPre = (function (_super) {
  15243. __extends(PointerInfoPre, _super);
  15244. function PointerInfoPre(type, event, localX, localY) {
  15245. var _this = _super.call(this, type, event) || this;
  15246. _this.skipOnPointerObservable = false;
  15247. _this.localPosition = new BABYLON.Vector2(localX, localY);
  15248. return _this;
  15249. }
  15250. return PointerInfoPre;
  15251. }(PointerInfoBase));
  15252. BABYLON.PointerInfoPre = PointerInfoPre;
  15253. /**
  15254. * This type contains all the data related to a pointer event in Babylon.js.
  15255. * 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.
  15256. */
  15257. var PointerInfo = (function (_super) {
  15258. __extends(PointerInfo, _super);
  15259. function PointerInfo(type, event, pickInfo) {
  15260. var _this = _super.call(this, type, event) || this;
  15261. _this.pickInfo = pickInfo;
  15262. return _this;
  15263. }
  15264. return PointerInfo;
  15265. }(PointerInfoBase));
  15266. BABYLON.PointerInfo = PointerInfo;
  15267. /**
  15268. * This class is used by the onRenderingGroupObservable
  15269. */
  15270. var RenderingGroupInfo = (function () {
  15271. function RenderingGroupInfo() {
  15272. }
  15273. return RenderingGroupInfo;
  15274. }());
  15275. /**
  15276. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  15277. * This stage will be fired no matter what
  15278. */
  15279. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  15280. /**
  15281. * Called before opaque object are rendered.
  15282. * This stage will be fired only if there's 3D Opaque content to render
  15283. */
  15284. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  15285. /**
  15286. * Called after the opaque objects are rendered and before the transparent ones
  15287. * This stage will be fired only if there's 3D transparent content to render
  15288. */
  15289. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  15290. /**
  15291. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  15292. * This stage will be fired no matter what
  15293. */
  15294. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  15295. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  15296. /**
  15297. * Represents a scene to be rendered by the engine.
  15298. * @see http://doc.babylonjs.com/page.php?p=21911
  15299. */
  15300. var Scene = (function () {
  15301. /**
  15302. * @constructor
  15303. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  15304. */
  15305. function Scene(engine) {
  15306. // Members
  15307. this.autoClear = true;
  15308. this.autoClearDepthAndStencil = true;
  15309. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  15310. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  15311. this.forceWireframe = false;
  15312. this._forcePointsCloud = false;
  15313. this.forceShowBoundingBoxes = false;
  15314. this.animationsEnabled = true;
  15315. this.constantlyUpdateMeshUnderPointer = false;
  15316. this.hoverCursor = "pointer";
  15317. // Metadata
  15318. this.metadata = null;
  15319. // Events
  15320. /**
  15321. * An event triggered when the scene is disposed.
  15322. * @type {BABYLON.Observable}
  15323. */
  15324. this.onDisposeObservable = new BABYLON.Observable();
  15325. /**
  15326. * An event triggered before rendering the scene
  15327. * @type {BABYLON.Observable}
  15328. */
  15329. this.onBeforeRenderObservable = new BABYLON.Observable();
  15330. /**
  15331. * An event triggered after rendering the scene
  15332. * @type {BABYLON.Observable}
  15333. */
  15334. this.onAfterRenderObservable = new BABYLON.Observable();
  15335. /**
  15336. * An event triggered when the scene is ready
  15337. * @type {BABYLON.Observable}
  15338. */
  15339. this.onReadyObservable = new BABYLON.Observable();
  15340. /**
  15341. * An event triggered before rendering a camera
  15342. * @type {BABYLON.Observable}
  15343. */
  15344. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  15345. /**
  15346. * An event triggered after rendering a camera
  15347. * @type {BABYLON.Observable}
  15348. */
  15349. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  15350. /**
  15351. * An event triggered when a camera is created
  15352. * @type {BABYLON.Observable}
  15353. */
  15354. this.onNewCameraAddedObservable = new BABYLON.Observable();
  15355. /**
  15356. * An event triggered when a camera is removed
  15357. * @type {BABYLON.Observable}
  15358. */
  15359. this.onCameraRemovedObservable = new BABYLON.Observable();
  15360. /**
  15361. * An event triggered when a light is created
  15362. * @type {BABYLON.Observable}
  15363. */
  15364. this.onNewLightAddedObservable = new BABYLON.Observable();
  15365. /**
  15366. * An event triggered when a light is removed
  15367. * @type {BABYLON.Observable}
  15368. */
  15369. this.onLightRemovedObservable = new BABYLON.Observable();
  15370. /**
  15371. * An event triggered when a geometry is created
  15372. * @type {BABYLON.Observable}
  15373. */
  15374. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  15375. /**
  15376. * An event triggered when a geometry is removed
  15377. * @type {BABYLON.Observable}
  15378. */
  15379. this.onGeometryRemovedObservable = new BABYLON.Observable();
  15380. /**
  15381. * An event triggered when a mesh is created
  15382. * @type {BABYLON.Observable}
  15383. */
  15384. this.onNewMeshAddedObservable = new BABYLON.Observable();
  15385. /**
  15386. * An event triggered when a mesh is removed
  15387. * @type {BABYLON.Observable}
  15388. */
  15389. this.onMeshRemovedObservable = new BABYLON.Observable();
  15390. /**
  15391. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  15392. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  15393. * 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)
  15394. */
  15395. this.onRenderingGroupObservable = new BABYLON.Observable();
  15396. // Animations
  15397. this.animations = [];
  15398. /**
  15399. * 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).
  15400. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  15401. */
  15402. this.onPrePointerObservable = new BABYLON.Observable();
  15403. /**
  15404. * Observable event triggered each time an input event is received from the rendering canvas
  15405. */
  15406. this.onPointerObservable = new BABYLON.Observable();
  15407. this._meshPickProceed = false;
  15408. this._previousHasSwiped = false;
  15409. this._currentPickResult = null;
  15410. this._previousPickResult = null;
  15411. this._isButtonPressed = false;
  15412. this._doubleClickOccured = false;
  15413. 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
  15414. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  15415. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  15416. this._startingPointerTime = 0;
  15417. this._previousStartingPointerTime = 0;
  15418. // Coordinate system
  15419. /**
  15420. * use right-handed coordinate system on this scene.
  15421. * @type {boolean}
  15422. */
  15423. this._useRightHandedSystem = false;
  15424. // Fog
  15425. /**
  15426. * is fog enabled on this scene.
  15427. * @type {boolean}
  15428. */
  15429. this._fogEnabled = true;
  15430. this._fogMode = Scene.FOGMODE_NONE;
  15431. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15432. this.fogDensity = 0.1;
  15433. this.fogStart = 0;
  15434. this.fogEnd = 1000.0;
  15435. // Lights
  15436. /**
  15437. * is shadow enabled on this scene.
  15438. * @type {boolean}
  15439. */
  15440. this._shadowsEnabled = true;
  15441. /**
  15442. * is light enabled on this scene.
  15443. * @type {boolean}
  15444. */
  15445. this._lightsEnabled = true;
  15446. /**
  15447. * All of the lights added to this scene.
  15448. * @see BABYLON.Light
  15449. * @type {BABYLON.Light[]}
  15450. */
  15451. this.lights = new Array();
  15452. // Cameras
  15453. /**
  15454. * All of the cameras added to this scene.
  15455. * @see BABYLON.Camera
  15456. * @type {BABYLON.Camera[]}
  15457. */
  15458. this.cameras = new Array();
  15459. this.activeCameras = new Array();
  15460. // Meshes
  15461. /**
  15462. * All of the (abstract) meshes added to this scene.
  15463. * @see BABYLON.AbstractMesh
  15464. * @type {BABYLON.AbstractMesh[]}
  15465. */
  15466. this.meshes = new Array();
  15467. // Geometries
  15468. this._geometries = new Array();
  15469. this.materials = new Array();
  15470. this.multiMaterials = new Array();
  15471. // Textures
  15472. this._texturesEnabled = true;
  15473. this.textures = new Array();
  15474. // Particles
  15475. this.particlesEnabled = true;
  15476. this.particleSystems = new Array();
  15477. // Sprites
  15478. this.spritesEnabled = true;
  15479. this.spriteManagers = new Array();
  15480. // Layers
  15481. this.layers = new Array();
  15482. this.highlightLayers = new Array();
  15483. // Skeletons
  15484. this._skeletonsEnabled = true;
  15485. this.skeletons = new Array();
  15486. // Morph targets
  15487. this.morphTargetManagers = new Array();
  15488. // Lens flares
  15489. this.lensFlaresEnabled = true;
  15490. this.lensFlareSystems = new Array();
  15491. // Collisions
  15492. this.collisionsEnabled = true;
  15493. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  15494. // Postprocesses
  15495. this.postProcessesEnabled = true;
  15496. // Customs render targets
  15497. this.renderTargetsEnabled = true;
  15498. this.dumpNextRenderTargets = false;
  15499. this.customRenderTargets = new Array();
  15500. // Imported meshes
  15501. this.importedMeshesFiles = new Array();
  15502. // Probes
  15503. this.probesEnabled = true;
  15504. this.reflectionProbes = new Array();
  15505. this._actionManagers = new Array();
  15506. this._meshesForIntersections = new BABYLON.SmartArray(256);
  15507. // Procedural textures
  15508. this.proceduralTexturesEnabled = true;
  15509. this._proceduralTextures = new Array();
  15510. this.soundTracks = new Array();
  15511. this._audioEnabled = true;
  15512. this._headphone = false;
  15513. // Performance counters
  15514. this._totalMeshesCounter = new BABYLON.PerfCounter();
  15515. this._totalLightsCounter = new BABYLON.PerfCounter();
  15516. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  15517. this._totalTexturesCounter = new BABYLON.PerfCounter();
  15518. this._totalVertices = new BABYLON.PerfCounter();
  15519. this._activeIndices = new BABYLON.PerfCounter();
  15520. this._activeParticles = new BABYLON.PerfCounter();
  15521. this._lastFrameDuration = new BABYLON.PerfCounter();
  15522. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  15523. this._renderTargetsDuration = new BABYLON.PerfCounter();
  15524. this._particlesDuration = new BABYLON.PerfCounter();
  15525. this._renderDuration = new BABYLON.PerfCounter();
  15526. this._spritesDuration = new BABYLON.PerfCounter();
  15527. this._activeBones = new BABYLON.PerfCounter();
  15528. this._animationTime = 0;
  15529. this.animationTimeScale = 1;
  15530. this._renderId = 0;
  15531. this._executeWhenReadyTimeoutId = -1;
  15532. this._intermediateRendering = false;
  15533. this._viewUpdateFlag = -1;
  15534. this._projectionUpdateFlag = -1;
  15535. this._toBeDisposed = new BABYLON.SmartArray(256);
  15536. this._pendingData = []; //ANY
  15537. this._activeMeshes = new BABYLON.SmartArray(256);
  15538. this._processedMaterials = new BABYLON.SmartArray(256);
  15539. this._renderTargets = new BABYLON.SmartArray(256);
  15540. this._activeParticleSystems = new BABYLON.SmartArray(256);
  15541. this._activeSkeletons = new BABYLON.SmartArray(32);
  15542. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  15543. this._activeAnimatables = new Array();
  15544. this._transformMatrix = BABYLON.Matrix.Zero();
  15545. this.requireLightSorting = false;
  15546. this._uniqueIdCounter = 0;
  15547. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  15548. this._engine.scenes.push(this);
  15549. this._uid = null;
  15550. this._renderingManager = new BABYLON.RenderingManager(this);
  15551. this.postProcessManager = new BABYLON.PostProcessManager(this);
  15552. if (BABYLON.OutlineRenderer) {
  15553. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  15554. }
  15555. this.attachControl();
  15556. if (BABYLON.SoundTrack) {
  15557. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  15558. }
  15559. //simplification queue
  15560. if (BABYLON.SimplificationQueue) {
  15561. this.simplificationQueue = new BABYLON.SimplificationQueue();
  15562. }
  15563. //collision coordinator initialization. For now legacy per default.
  15564. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  15565. // Uniform Buffer
  15566. this._createUbo();
  15567. }
  15568. Object.defineProperty(Scene, "FOGMODE_NONE", {
  15569. get: function () {
  15570. return Scene._FOGMODE_NONE;
  15571. },
  15572. enumerable: true,
  15573. configurable: true
  15574. });
  15575. Object.defineProperty(Scene, "FOGMODE_EXP", {
  15576. get: function () {
  15577. return Scene._FOGMODE_EXP;
  15578. },
  15579. enumerable: true,
  15580. configurable: true
  15581. });
  15582. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  15583. get: function () {
  15584. return Scene._FOGMODE_EXP2;
  15585. },
  15586. enumerable: true,
  15587. configurable: true
  15588. });
  15589. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  15590. get: function () {
  15591. return Scene._FOGMODE_LINEAR;
  15592. },
  15593. enumerable: true,
  15594. configurable: true
  15595. });
  15596. Object.defineProperty(Scene.prototype, "environmentTexture", {
  15597. /**
  15598. * Texture used in all pbr material as the reflection texture.
  15599. * As in the majority of the scene they are the same (exception for multi room and so on),
  15600. * this is easier to reference from here than from all the materials.
  15601. */
  15602. get: function () {
  15603. return this._environmentTexture;
  15604. },
  15605. /**
  15606. * Texture used in all pbr material as the reflection texture.
  15607. * As in the majority of the scene they are the same (exception for multi room and so on),
  15608. * this is easier to set here than in all the materials.
  15609. */
  15610. set: function (value) {
  15611. this._environmentTexture = value;
  15612. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  15613. },
  15614. enumerable: true,
  15615. configurable: true
  15616. });
  15617. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  15618. get: function () {
  15619. return this._forcePointsCloud;
  15620. },
  15621. set: function (value) {
  15622. if (this._forcePointsCloud === value) {
  15623. return;
  15624. }
  15625. this._forcePointsCloud = value;
  15626. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15627. },
  15628. enumerable: true,
  15629. configurable: true
  15630. });
  15631. Object.defineProperty(Scene.prototype, "onDispose", {
  15632. set: function (callback) {
  15633. if (this._onDisposeObserver) {
  15634. this.onDisposeObservable.remove(this._onDisposeObserver);
  15635. }
  15636. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15637. },
  15638. enumerable: true,
  15639. configurable: true
  15640. });
  15641. Object.defineProperty(Scene.prototype, "beforeRender", {
  15642. set: function (callback) {
  15643. if (this._onBeforeRenderObserver) {
  15644. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  15645. }
  15646. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  15647. },
  15648. enumerable: true,
  15649. configurable: true
  15650. });
  15651. Object.defineProperty(Scene.prototype, "afterRender", {
  15652. set: function (callback) {
  15653. if (this._onAfterRenderObserver) {
  15654. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  15655. }
  15656. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  15657. },
  15658. enumerable: true,
  15659. configurable: true
  15660. });
  15661. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  15662. set: function (callback) {
  15663. if (this._onBeforeCameraRenderObserver) {
  15664. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  15665. }
  15666. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  15667. },
  15668. enumerable: true,
  15669. configurable: true
  15670. });
  15671. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  15672. set: function (callback) {
  15673. if (this._onAfterCameraRenderObserver) {
  15674. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  15675. }
  15676. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  15677. },
  15678. enumerable: true,
  15679. configurable: true
  15680. });
  15681. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  15682. get: function () {
  15683. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  15684. },
  15685. enumerable: true,
  15686. configurable: true
  15687. });
  15688. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  15689. get: function () {
  15690. return this._useRightHandedSystem;
  15691. },
  15692. set: function (value) {
  15693. if (this._useRightHandedSystem === value) {
  15694. return;
  15695. }
  15696. this._useRightHandedSystem = value;
  15697. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15698. },
  15699. enumerable: true,
  15700. configurable: true
  15701. });
  15702. Object.defineProperty(Scene.prototype, "fogEnabled", {
  15703. get: function () {
  15704. return this._fogEnabled;
  15705. },
  15706. set: function (value) {
  15707. if (this._fogEnabled === value) {
  15708. return;
  15709. }
  15710. this._fogEnabled = value;
  15711. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15712. },
  15713. enumerable: true,
  15714. configurable: true
  15715. });
  15716. Object.defineProperty(Scene.prototype, "fogMode", {
  15717. get: function () {
  15718. return this._fogMode;
  15719. },
  15720. set: function (value) {
  15721. if (this._fogMode === value) {
  15722. return;
  15723. }
  15724. this._fogMode = value;
  15725. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15726. },
  15727. enumerable: true,
  15728. configurable: true
  15729. });
  15730. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  15731. get: function () {
  15732. return this._shadowsEnabled;
  15733. },
  15734. set: function (value) {
  15735. if (this._shadowsEnabled === value) {
  15736. return;
  15737. }
  15738. this._shadowsEnabled = value;
  15739. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  15740. },
  15741. enumerable: true,
  15742. configurable: true
  15743. });
  15744. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  15745. get: function () {
  15746. return this._lightsEnabled;
  15747. },
  15748. set: function (value) {
  15749. if (this._lightsEnabled === value) {
  15750. return;
  15751. }
  15752. this._lightsEnabled = value;
  15753. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  15754. },
  15755. enumerable: true,
  15756. configurable: true
  15757. });
  15758. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  15759. get: function () {
  15760. if (!this._defaultMaterial) {
  15761. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  15762. }
  15763. return this._defaultMaterial;
  15764. },
  15765. set: function (value) {
  15766. this._defaultMaterial = value;
  15767. },
  15768. enumerable: true,
  15769. configurable: true
  15770. });
  15771. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  15772. get: function () {
  15773. return this._texturesEnabled;
  15774. },
  15775. set: function (value) {
  15776. if (this._texturesEnabled === value) {
  15777. return;
  15778. }
  15779. this._texturesEnabled = value;
  15780. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  15781. },
  15782. enumerable: true,
  15783. configurable: true
  15784. });
  15785. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  15786. get: function () {
  15787. return this._skeletonsEnabled;
  15788. },
  15789. set: function (value) {
  15790. if (this._skeletonsEnabled === value) {
  15791. return;
  15792. }
  15793. this._skeletonsEnabled = value;
  15794. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  15795. },
  15796. enumerable: true,
  15797. configurable: true
  15798. });
  15799. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  15800. get: function () {
  15801. if (!this._postProcessRenderPipelineManager) {
  15802. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  15803. }
  15804. return this._postProcessRenderPipelineManager;
  15805. },
  15806. enumerable: true,
  15807. configurable: true
  15808. });
  15809. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  15810. get: function () {
  15811. return this._frustumPlanes;
  15812. },
  15813. enumerable: true,
  15814. configurable: true
  15815. });
  15816. Object.defineProperty(Scene.prototype, "debugLayer", {
  15817. // Properties
  15818. get: function () {
  15819. if (!this._debugLayer) {
  15820. this._debugLayer = new BABYLON.DebugLayer(this);
  15821. }
  15822. return this._debugLayer;
  15823. },
  15824. enumerable: true,
  15825. configurable: true
  15826. });
  15827. Object.defineProperty(Scene.prototype, "workerCollisions", {
  15828. get: function () {
  15829. return this._workerCollisions;
  15830. },
  15831. set: function (enabled) {
  15832. if (!BABYLON.CollisionCoordinatorLegacy) {
  15833. return;
  15834. }
  15835. enabled = (enabled && !!Worker);
  15836. this._workerCollisions = enabled;
  15837. if (this.collisionCoordinator) {
  15838. this.collisionCoordinator.destroy();
  15839. }
  15840. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  15841. this.collisionCoordinator.init(this);
  15842. },
  15843. enumerable: true,
  15844. configurable: true
  15845. });
  15846. Object.defineProperty(Scene.prototype, "selectionOctree", {
  15847. get: function () {
  15848. return this._selectionOctree;
  15849. },
  15850. enumerable: true,
  15851. configurable: true
  15852. });
  15853. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  15854. /**
  15855. * The mesh that is currently under the pointer.
  15856. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  15857. */
  15858. get: function () {
  15859. return this._pointerOverMesh;
  15860. },
  15861. enumerable: true,
  15862. configurable: true
  15863. });
  15864. Object.defineProperty(Scene.prototype, "pointerX", {
  15865. /**
  15866. * Current on-screen X position of the pointer
  15867. * @return {number} X position of the pointer
  15868. */
  15869. get: function () {
  15870. return this._pointerX;
  15871. },
  15872. enumerable: true,
  15873. configurable: true
  15874. });
  15875. Object.defineProperty(Scene.prototype, "pointerY", {
  15876. /**
  15877. * Current on-screen Y position of the pointer
  15878. * @return {number} Y position of the pointer
  15879. */
  15880. get: function () {
  15881. return this._pointerY;
  15882. },
  15883. enumerable: true,
  15884. configurable: true
  15885. });
  15886. Scene.prototype.getCachedMaterial = function () {
  15887. return this._cachedMaterial;
  15888. };
  15889. Scene.prototype.getCachedEffect = function () {
  15890. return this._cachedEffect;
  15891. };
  15892. Scene.prototype.getCachedVisibility = function () {
  15893. return this._cachedVisibility;
  15894. };
  15895. Scene.prototype.isCachedMaterialValid = function (material, effect, visibility) {
  15896. if (visibility === void 0) { visibility = 0; }
  15897. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  15898. };
  15899. Scene.prototype.getBoundingBoxRenderer = function () {
  15900. if (!this._boundingBoxRenderer) {
  15901. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  15902. }
  15903. return this._boundingBoxRenderer;
  15904. };
  15905. Scene.prototype.getOutlineRenderer = function () {
  15906. return this._outlineRenderer;
  15907. };
  15908. Scene.prototype.getEngine = function () {
  15909. return this._engine;
  15910. };
  15911. Scene.prototype.getTotalVertices = function () {
  15912. return this._totalVertices.current;
  15913. };
  15914. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  15915. get: function () {
  15916. return this._totalVertices;
  15917. },
  15918. enumerable: true,
  15919. configurable: true
  15920. });
  15921. Scene.prototype.getActiveIndices = function () {
  15922. return this._activeIndices.current;
  15923. };
  15924. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  15925. get: function () {
  15926. return this._activeIndices;
  15927. },
  15928. enumerable: true,
  15929. configurable: true
  15930. });
  15931. Scene.prototype.getActiveParticles = function () {
  15932. return this._activeParticles.current;
  15933. };
  15934. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  15935. get: function () {
  15936. return this._activeParticles;
  15937. },
  15938. enumerable: true,
  15939. configurable: true
  15940. });
  15941. Scene.prototype.getActiveBones = function () {
  15942. return this._activeBones.current;
  15943. };
  15944. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  15945. get: function () {
  15946. return this._activeBones;
  15947. },
  15948. enumerable: true,
  15949. configurable: true
  15950. });
  15951. // Stats
  15952. Scene.prototype.getLastFrameDuration = function () {
  15953. return this._lastFrameDuration.current;
  15954. };
  15955. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  15956. get: function () {
  15957. return this._lastFrameDuration;
  15958. },
  15959. enumerable: true,
  15960. configurable: true
  15961. });
  15962. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  15963. return this._evaluateActiveMeshesDuration.current;
  15964. };
  15965. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  15966. get: function () {
  15967. return this._evaluateActiveMeshesDuration;
  15968. },
  15969. enumerable: true,
  15970. configurable: true
  15971. });
  15972. Scene.prototype.getActiveMeshes = function () {
  15973. return this._activeMeshes;
  15974. };
  15975. Scene.prototype.getRenderTargetsDuration = function () {
  15976. return this._renderTargetsDuration.current;
  15977. };
  15978. Scene.prototype.getRenderDuration = function () {
  15979. return this._renderDuration.current;
  15980. };
  15981. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  15982. get: function () {
  15983. return this._renderDuration;
  15984. },
  15985. enumerable: true,
  15986. configurable: true
  15987. });
  15988. Scene.prototype.getParticlesDuration = function () {
  15989. return this._particlesDuration.current;
  15990. };
  15991. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  15992. get: function () {
  15993. return this._particlesDuration;
  15994. },
  15995. enumerable: true,
  15996. configurable: true
  15997. });
  15998. Scene.prototype.getSpritesDuration = function () {
  15999. return this._spritesDuration.current;
  16000. };
  16001. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  16002. get: function () {
  16003. return this._spritesDuration;
  16004. },
  16005. enumerable: true,
  16006. configurable: true
  16007. });
  16008. Scene.prototype.getAnimationRatio = function () {
  16009. return this._animationRatio;
  16010. };
  16011. Scene.prototype.getRenderId = function () {
  16012. return this._renderId;
  16013. };
  16014. Scene.prototype.incrementRenderId = function () {
  16015. this._renderId++;
  16016. };
  16017. Scene.prototype._updatePointerPosition = function (evt) {
  16018. var canvasRect = this._engine.getRenderingCanvasClientRect();
  16019. this._pointerX = evt.clientX - canvasRect.left;
  16020. this._pointerY = evt.clientY - canvasRect.top;
  16021. this._unTranslatedPointerX = this._pointerX;
  16022. this._unTranslatedPointerY = this._pointerY;
  16023. if (this.cameraToUseForPointers) {
  16024. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  16025. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  16026. }
  16027. };
  16028. Scene.prototype._createUbo = function () {
  16029. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  16030. this._sceneUbo.addUniform("viewProjection", 16);
  16031. this._sceneUbo.addUniform("view", 16);
  16032. };
  16033. // Pointers handling
  16034. /**
  16035. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  16036. * @param attachUp defines if you want to attach events to pointerup
  16037. * @param attachDown defines if you want to attach events to pointerdown
  16038. * @param attachMove defines if you want to attach events to pointermove
  16039. */
  16040. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  16041. var _this = this;
  16042. if (attachUp === void 0) { attachUp = true; }
  16043. if (attachDown === void 0) { attachDown = true; }
  16044. if (attachMove === void 0) { attachMove = true; }
  16045. this._initActionManager = function (act, clickInfo) {
  16046. if (!_this._meshPickProceed) {
  16047. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16048. _this._currentPickResult = pickResult;
  16049. if (pickResult) {
  16050. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  16051. }
  16052. _this._meshPickProceed = true;
  16053. }
  16054. return act;
  16055. };
  16056. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  16057. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  16058. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  16059. btn !== _this._previousButtonPressed) {
  16060. _this._doubleClickOccured = false;
  16061. clickInfo.singleClick = true;
  16062. clickInfo.ignore = false;
  16063. cb(clickInfo, _this._currentPickResult);
  16064. }
  16065. };
  16066. this._initClickEvent = function (obs1, obs2, evt, cb) {
  16067. var clickInfo = new ClickInfo();
  16068. _this._currentPickResult = null;
  16069. var act;
  16070. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  16071. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  16072. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16073. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  16074. act = _this._initActionManager(act, clickInfo);
  16075. if (act)
  16076. checkPicking = act.hasPickTriggers;
  16077. }
  16078. if (checkPicking) {
  16079. var btn = evt.button;
  16080. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  16081. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  16082. if (!clickInfo.hasSwiped) {
  16083. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  16084. if (!checkSingleClickImmediately) {
  16085. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  16086. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16087. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16088. act = _this._initActionManager(act, clickInfo);
  16089. if (act)
  16090. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16091. }
  16092. }
  16093. if (checkSingleClickImmediately) {
  16094. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  16095. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  16096. btn !== _this._previousButtonPressed) {
  16097. clickInfo.singleClick = true;
  16098. cb(clickInfo, _this._currentPickResult);
  16099. }
  16100. }
  16101. else {
  16102. // wait that no double click has been raised during the double click delay
  16103. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16104. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  16105. }
  16106. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  16107. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16108. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16109. act = _this._initActionManager(act, clickInfo);
  16110. if (act)
  16111. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16112. }
  16113. if (checkDoubleClick) {
  16114. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  16115. if (btn === _this._previousButtonPressed &&
  16116. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  16117. !_this._doubleClickOccured) {
  16118. // pointer has not moved for 2 clicks, it's a double click
  16119. if (!clickInfo.hasSwiped &&
  16120. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  16121. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  16122. _this._previousStartingPointerTime = 0;
  16123. _this._doubleClickOccured = true;
  16124. clickInfo.doubleClick = true;
  16125. clickInfo.ignore = false;
  16126. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  16127. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16128. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16129. cb(clickInfo, _this._currentPickResult);
  16130. }
  16131. else {
  16132. _this._doubleClickOccured = false;
  16133. _this._previousStartingPointerTime = _this._startingPointerTime;
  16134. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16135. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16136. _this._previousButtonPressed = btn;
  16137. _this._previousHasSwiped = clickInfo.hasSwiped;
  16138. if (Scene.ExclusiveDoubleClickMode) {
  16139. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  16140. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16141. }
  16142. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16143. cb(clickInfo, _this._previousPickResult);
  16144. }
  16145. else {
  16146. cb(clickInfo, _this._currentPickResult);
  16147. }
  16148. }
  16149. }
  16150. else {
  16151. _this._doubleClickOccured = false;
  16152. _this._previousStartingPointerTime = _this._startingPointerTime;
  16153. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16154. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16155. _this._previousButtonPressed = btn;
  16156. _this._previousHasSwiped = clickInfo.hasSwiped;
  16157. }
  16158. }
  16159. }
  16160. }
  16161. clickInfo.ignore = true;
  16162. cb(clickInfo, _this._currentPickResult);
  16163. };
  16164. var spritePredicate = function (sprite) {
  16165. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  16166. };
  16167. this._onPointerMove = function (evt) {
  16168. _this._updatePointerPosition(evt);
  16169. // PreObservable support
  16170. if (_this.onPrePointerObservable.hasObservers()) {
  16171. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16172. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16173. _this.onPrePointerObservable.notifyObservers(pi, type);
  16174. if (pi.skipOnPointerObservable) {
  16175. return;
  16176. }
  16177. }
  16178. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16179. return;
  16180. }
  16181. var canvas = _this._engine.getRenderingCanvas();
  16182. if (!_this.pointerMovePredicate) {
  16183. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (_this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  16184. }
  16185. // Meshes
  16186. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  16187. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16188. _this.setPointerOverSprite(null);
  16189. _this.setPointerOverMesh(pickResult.pickedMesh);
  16190. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  16191. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  16192. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  16193. }
  16194. else {
  16195. canvas.style.cursor = _this.hoverCursor;
  16196. }
  16197. }
  16198. else {
  16199. canvas.style.cursor = "";
  16200. }
  16201. }
  16202. else {
  16203. _this.setPointerOverMesh(null);
  16204. // Sprites
  16205. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16206. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16207. _this.setPointerOverSprite(pickResult.pickedSprite);
  16208. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  16209. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  16210. }
  16211. else {
  16212. canvas.style.cursor = _this.hoverCursor;
  16213. }
  16214. }
  16215. else {
  16216. _this.setPointerOverSprite(null);
  16217. // Restore pointer
  16218. canvas.style.cursor = "";
  16219. }
  16220. }
  16221. if (_this.onPointerMove) {
  16222. _this.onPointerMove(evt, pickResult);
  16223. }
  16224. if (_this.onPointerObservable.hasObservers()) {
  16225. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16226. var pi = new PointerInfo(type, evt, pickResult);
  16227. _this.onPointerObservable.notifyObservers(pi, type);
  16228. }
  16229. };
  16230. this._onPointerDown = function (evt) {
  16231. _this._isButtonPressed = true;
  16232. _this._pickedDownMesh = null;
  16233. _this._meshPickProceed = false;
  16234. _this._updatePointerPosition(evt);
  16235. // PreObservable support
  16236. if (_this.onPrePointerObservable.hasObservers()) {
  16237. var type = PointerEventTypes.POINTERDOWN;
  16238. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16239. _this.onPrePointerObservable.notifyObservers(pi, type);
  16240. if (pi.skipOnPointerObservable) {
  16241. return;
  16242. }
  16243. }
  16244. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16245. return;
  16246. }
  16247. _this._startingPointerPosition.x = _this._pointerX;
  16248. _this._startingPointerPosition.y = _this._pointerY;
  16249. _this._startingPointerTime = new Date().getTime();
  16250. if (!_this.pointerDownPredicate) {
  16251. _this.pointerDownPredicate = function (mesh) {
  16252. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16253. };
  16254. }
  16255. // Meshes
  16256. _this._pickedDownMesh = null;
  16257. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16258. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16259. _this._pickedDownMesh = pickResult.pickedMesh;
  16260. var actionManager = pickResult.pickedMesh.actionManager;
  16261. if (actionManager) {
  16262. if (actionManager.hasPickTriggers) {
  16263. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16264. switch (evt.button) {
  16265. case 0:
  16266. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16267. break;
  16268. case 1:
  16269. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16270. break;
  16271. case 2:
  16272. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16273. break;
  16274. }
  16275. }
  16276. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  16277. window.setTimeout((function () {
  16278. var _this = this;
  16279. 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);
  16280. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16281. if (this._isButtonPressed &&
  16282. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  16283. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  16284. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  16285. this._startingPointerTime = 0;
  16286. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16287. }
  16288. }
  16289. }).bind(_this), Scene.LongPressDelay);
  16290. }
  16291. }
  16292. }
  16293. if (_this.onPointerDown) {
  16294. _this.onPointerDown(evt, pickResult);
  16295. }
  16296. if (_this.onPointerObservable.hasObservers()) {
  16297. var type = PointerEventTypes.POINTERDOWN;
  16298. var pi = new PointerInfo(type, evt, pickResult);
  16299. _this.onPointerObservable.notifyObservers(pi, type);
  16300. }
  16301. // Sprites
  16302. _this._pickedDownSprite = null;
  16303. if (_this.spriteManagers.length > 0) {
  16304. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16305. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16306. if (pickResult.pickedSprite.actionManager) {
  16307. _this._pickedDownSprite = pickResult.pickedSprite;
  16308. switch (evt.button) {
  16309. case 0:
  16310. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16311. break;
  16312. case 1:
  16313. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16314. break;
  16315. case 2:
  16316. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16317. break;
  16318. }
  16319. if (pickResult.pickedSprite.actionManager) {
  16320. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16321. }
  16322. }
  16323. }
  16324. }
  16325. };
  16326. this._onPointerUp = function (evt) {
  16327. _this._isButtonPressed = false;
  16328. _this._pickedUpMesh = null;
  16329. _this._meshPickProceed = false;
  16330. _this._updatePointerPosition(evt);
  16331. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  16332. // PreObservable support
  16333. if (this.onPrePointerObservable.hasObservers()) {
  16334. if (!clickInfo.ignore) {
  16335. if (!clickInfo.hasSwiped) {
  16336. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16337. var type = PointerEventTypes.POINTERTAP;
  16338. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16339. this.onPrePointerObservable.notifyObservers(pi, type);
  16340. if (pi.skipOnPointerObservable) {
  16341. return;
  16342. }
  16343. }
  16344. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16345. var type = PointerEventTypes.POINTERDOUBLETAP;
  16346. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16347. this.onPrePointerObservable.notifyObservers(pi, type);
  16348. if (pi.skipOnPointerObservable) {
  16349. return;
  16350. }
  16351. }
  16352. }
  16353. }
  16354. else {
  16355. var type = PointerEventTypes.POINTERUP;
  16356. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16357. this.onPrePointerObservable.notifyObservers(pi, type);
  16358. if (pi.skipOnPointerObservable) {
  16359. return;
  16360. }
  16361. }
  16362. }
  16363. if (!this.cameraToUseForPointers && !this.activeCamera) {
  16364. return;
  16365. }
  16366. if (!this.pointerUpPredicate) {
  16367. this.pointerUpPredicate = function (mesh) {
  16368. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16369. };
  16370. }
  16371. // Meshes
  16372. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  16373. this._initActionManager(null, clickInfo);
  16374. }
  16375. if (!pickResult) {
  16376. pickResult = this._currentPickResult;
  16377. }
  16378. if (pickResult && pickResult && pickResult.pickedMesh) {
  16379. this._pickedUpMesh = pickResult.pickedMesh;
  16380. if (this._pickedDownMesh === this._pickedUpMesh) {
  16381. if (this.onPointerPick) {
  16382. this.onPointerPick(evt, pickResult);
  16383. }
  16384. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  16385. var type = PointerEventTypes.POINTERPICK;
  16386. var pi = new PointerInfo(type, evt, pickResult);
  16387. this.onPointerObservable.notifyObservers(pi, type);
  16388. }
  16389. }
  16390. if (pickResult.pickedMesh.actionManager) {
  16391. if (clickInfo.ignore) {
  16392. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16393. }
  16394. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  16395. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16396. }
  16397. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16398. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16399. }
  16400. }
  16401. }
  16402. if (this._pickedDownMesh &&
  16403. this._pickedDownMesh.actionManager &&
  16404. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  16405. this._pickedDownMesh !== this._pickedUpMesh) {
  16406. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  16407. }
  16408. if (this.onPointerUp) {
  16409. this.onPointerUp(evt, pickResult);
  16410. }
  16411. if (this.onPointerObservable.hasObservers()) {
  16412. if (!clickInfo.ignore) {
  16413. if (!clickInfo.hasSwiped) {
  16414. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16415. var type = PointerEventTypes.POINTERTAP;
  16416. var pi = new PointerInfo(type, evt, pickResult);
  16417. this.onPointerObservable.notifyObservers(pi, type);
  16418. }
  16419. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16420. var type = PointerEventTypes.POINTERDOUBLETAP;
  16421. var pi = new PointerInfo(type, evt, pickResult);
  16422. this.onPointerObservable.notifyObservers(pi, type);
  16423. }
  16424. }
  16425. }
  16426. else {
  16427. var type = PointerEventTypes.POINTERUP;
  16428. var pi = new PointerInfo(type, evt, pickResult);
  16429. this.onPointerObservable.notifyObservers(pi, type);
  16430. }
  16431. }
  16432. // Sprites
  16433. if (this.spriteManagers.length > 0) {
  16434. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  16435. if (pickResult.hit && pickResult.pickedSprite) {
  16436. if (pickResult.pickedSprite.actionManager) {
  16437. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  16438. if (pickResult.pickedSprite.actionManager) {
  16439. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  16440. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  16441. }
  16442. }
  16443. }
  16444. }
  16445. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  16446. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  16447. }
  16448. }
  16449. this._previousPickResult = this._currentPickResult;
  16450. }).bind(_this));
  16451. };
  16452. this._onKeyDown = function (evt) {
  16453. if (_this.actionManager) {
  16454. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16455. }
  16456. };
  16457. this._onKeyUp = function (evt) {
  16458. if (_this.actionManager) {
  16459. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16460. }
  16461. };
  16462. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16463. var canvas = this._engine.getRenderingCanvas();
  16464. if (attachMove) {
  16465. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  16466. // Wheel
  16467. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  16468. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  16469. }
  16470. if (attachDown) {
  16471. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  16472. }
  16473. if (attachUp) {
  16474. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  16475. }
  16476. canvas.tabIndex = 1;
  16477. canvas.addEventListener("keydown", this._onKeyDown, false);
  16478. canvas.addEventListener("keyup", this._onKeyUp, false);
  16479. };
  16480. Scene.prototype.detachControl = function () {
  16481. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16482. var canvas = this._engine.getRenderingCanvas();
  16483. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  16484. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  16485. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  16486. // Wheel
  16487. canvas.removeEventListener('mousewheel', this._onPointerMove);
  16488. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  16489. canvas.removeEventListener("keydown", this._onKeyDown);
  16490. canvas.removeEventListener("keyup", this._onKeyUp);
  16491. };
  16492. // Ready
  16493. Scene.prototype.isReady = function () {
  16494. if (this._pendingData.length > 0) {
  16495. return false;
  16496. }
  16497. var index;
  16498. // Geometries
  16499. for (index = 0; index < this._geometries.length; index++) {
  16500. var geometry = this._geometries[index];
  16501. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  16502. return false;
  16503. }
  16504. }
  16505. // Meshes
  16506. for (index = 0; index < this.meshes.length; index++) {
  16507. var mesh = this.meshes[index];
  16508. if (!mesh.isEnabled()) {
  16509. continue;
  16510. }
  16511. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  16512. continue;
  16513. }
  16514. if (!mesh.isReady()) {
  16515. return false;
  16516. }
  16517. var mat = mesh.material;
  16518. if (mat) {
  16519. if (!mat.isReady(mesh)) {
  16520. return false;
  16521. }
  16522. }
  16523. }
  16524. return true;
  16525. };
  16526. Scene.prototype.resetCachedMaterial = function () {
  16527. this._cachedMaterial = null;
  16528. this._cachedEffect = null;
  16529. this._cachedVisibility = null;
  16530. };
  16531. Scene.prototype.registerBeforeRender = function (func) {
  16532. this.onBeforeRenderObservable.add(func);
  16533. };
  16534. Scene.prototype.unregisterBeforeRender = function (func) {
  16535. this.onBeforeRenderObservable.removeCallback(func);
  16536. };
  16537. Scene.prototype.registerAfterRender = function (func) {
  16538. this.onAfterRenderObservable.add(func);
  16539. };
  16540. Scene.prototype.unregisterAfterRender = function (func) {
  16541. this.onAfterRenderObservable.removeCallback(func);
  16542. };
  16543. Scene.prototype._addPendingData = function (data) {
  16544. this._pendingData.push(data);
  16545. };
  16546. Scene.prototype._removePendingData = function (data) {
  16547. var index = this._pendingData.indexOf(data);
  16548. if (index !== -1) {
  16549. this._pendingData.splice(index, 1);
  16550. }
  16551. };
  16552. Scene.prototype.getWaitingItemsCount = function () {
  16553. return this._pendingData.length;
  16554. };
  16555. /**
  16556. * Registers a function to be executed when the scene is ready.
  16557. * @param {Function} func - the function to be executed.
  16558. */
  16559. Scene.prototype.executeWhenReady = function (func) {
  16560. var _this = this;
  16561. this.onReadyObservable.add(func);
  16562. if (this._executeWhenReadyTimeoutId !== -1) {
  16563. return;
  16564. }
  16565. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16566. _this._checkIsReady();
  16567. }, 150);
  16568. };
  16569. Scene.prototype._checkIsReady = function () {
  16570. var _this = this;
  16571. if (this.isReady()) {
  16572. this.onReadyObservable.notifyObservers(this);
  16573. this.onReadyObservable.clear();
  16574. this._executeWhenReadyTimeoutId = -1;
  16575. return;
  16576. }
  16577. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16578. _this._checkIsReady();
  16579. }, 150);
  16580. };
  16581. // Animations
  16582. /**
  16583. * Will start the animation sequence of a given target
  16584. * @param target - the target
  16585. * @param {number} from - from which frame should animation start
  16586. * @param {number} to - till which frame should animation run.
  16587. * @param {boolean} [loop] - should the animation loop
  16588. * @param {number} [speedRatio] - the speed in which to run the animation
  16589. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  16590. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  16591. * @return {BABYLON.Animatable} the animatable object created for this animation
  16592. * @see BABYLON.Animatable
  16593. * @see http://doc.babylonjs.com/page.php?p=22081
  16594. */
  16595. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  16596. if (speedRatio === void 0) { speedRatio = 1.0; }
  16597. if (from > to && speedRatio > 0) {
  16598. speedRatio *= -1;
  16599. }
  16600. this.stopAnimation(target);
  16601. if (!animatable) {
  16602. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  16603. }
  16604. // Local animations
  16605. if (target.animations) {
  16606. animatable.appendAnimations(target, target.animations);
  16607. }
  16608. // Children animations
  16609. if (target.getAnimatables) {
  16610. var animatables = target.getAnimatables();
  16611. for (var index = 0; index < animatables.length; index++) {
  16612. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  16613. }
  16614. }
  16615. animatable.reset();
  16616. return animatable;
  16617. };
  16618. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  16619. if (speedRatio === undefined) {
  16620. speedRatio = 1.0;
  16621. }
  16622. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  16623. return animatable;
  16624. };
  16625. Scene.prototype.getAnimatableByTarget = function (target) {
  16626. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16627. if (this._activeAnimatables[index].target === target) {
  16628. return this._activeAnimatables[index];
  16629. }
  16630. }
  16631. return null;
  16632. };
  16633. Object.defineProperty(Scene.prototype, "Animatables", {
  16634. get: function () {
  16635. return this._activeAnimatables;
  16636. },
  16637. enumerable: true,
  16638. configurable: true
  16639. });
  16640. /**
  16641. * Will stop the animation of the given target
  16642. * @param target - the target
  16643. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  16644. * @see beginAnimation
  16645. */
  16646. Scene.prototype.stopAnimation = function (target, animationName) {
  16647. var animatable = this.getAnimatableByTarget(target);
  16648. if (animatable) {
  16649. animatable.stop(animationName);
  16650. }
  16651. };
  16652. Scene.prototype._animate = function () {
  16653. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  16654. return;
  16655. }
  16656. // Getting time
  16657. var now = BABYLON.Tools.Now;
  16658. if (!this._animationTimeLast) {
  16659. if (this._pendingData.length > 0) {
  16660. return;
  16661. }
  16662. this._animationTimeLast = now;
  16663. }
  16664. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  16665. this._animationTime += deltaTime;
  16666. this._animationTimeLast = now;
  16667. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16668. this._activeAnimatables[index]._animate(this._animationTime);
  16669. }
  16670. };
  16671. // Matrix
  16672. Scene.prototype.getViewMatrix = function () {
  16673. return this._viewMatrix;
  16674. };
  16675. Scene.prototype.getProjectionMatrix = function () {
  16676. return this._projectionMatrix;
  16677. };
  16678. Scene.prototype.getTransformMatrix = function () {
  16679. return this._transformMatrix;
  16680. };
  16681. Scene.prototype.setTransformMatrix = function (view, projection) {
  16682. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  16683. return;
  16684. }
  16685. this._viewUpdateFlag = view.updateFlag;
  16686. this._projectionUpdateFlag = projection.updateFlag;
  16687. this._viewMatrix = view;
  16688. this._projectionMatrix = projection;
  16689. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16690. // Update frustum
  16691. if (!this._frustumPlanes) {
  16692. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16693. }
  16694. else {
  16695. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16696. }
  16697. if (this._sceneUbo.useUbo) {
  16698. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  16699. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  16700. this._sceneUbo.update();
  16701. }
  16702. };
  16703. Scene.prototype.getSceneUniformBuffer = function () {
  16704. return this._sceneUbo;
  16705. };
  16706. // Methods
  16707. Scene.prototype.getUniqueId = function () {
  16708. var result = this._uniqueIdCounter;
  16709. this._uniqueIdCounter++;
  16710. return result;
  16711. };
  16712. Scene.prototype.addMesh = function (newMesh) {
  16713. newMesh.uniqueId = this.getUniqueId();
  16714. var position = this.meshes.push(newMesh);
  16715. //notify the collision coordinator
  16716. if (this.collisionCoordinator) {
  16717. this.collisionCoordinator.onMeshAdded(newMesh);
  16718. }
  16719. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  16720. };
  16721. Scene.prototype.removeMesh = function (toRemove) {
  16722. var index = this.meshes.indexOf(toRemove);
  16723. if (index !== -1) {
  16724. // Remove from the scene if mesh found
  16725. this.meshes.splice(index, 1);
  16726. }
  16727. //notify the collision coordinator
  16728. if (this.collisionCoordinator) {
  16729. this.collisionCoordinator.onMeshRemoved(toRemove);
  16730. }
  16731. this.onMeshRemovedObservable.notifyObservers(toRemove);
  16732. return index;
  16733. };
  16734. Scene.prototype.removeSkeleton = function (toRemove) {
  16735. var index = this.skeletons.indexOf(toRemove);
  16736. if (index !== -1) {
  16737. // Remove from the scene if found
  16738. this.skeletons.splice(index, 1);
  16739. }
  16740. return index;
  16741. };
  16742. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  16743. var index = this.morphTargetManagers.indexOf(toRemove);
  16744. if (index !== -1) {
  16745. // Remove from the scene if found
  16746. this.morphTargetManagers.splice(index, 1);
  16747. }
  16748. return index;
  16749. };
  16750. Scene.prototype.removeLight = function (toRemove) {
  16751. var index = this.lights.indexOf(toRemove);
  16752. if (index !== -1) {
  16753. // Remove from the scene if mesh found
  16754. this.lights.splice(index, 1);
  16755. this.sortLightsByPriority();
  16756. }
  16757. this.onLightRemovedObservable.notifyObservers(toRemove);
  16758. return index;
  16759. };
  16760. Scene.prototype.removeCamera = function (toRemove) {
  16761. var index = this.cameras.indexOf(toRemove);
  16762. if (index !== -1) {
  16763. // Remove from the scene if mesh found
  16764. this.cameras.splice(index, 1);
  16765. }
  16766. // Remove from activeCameras
  16767. var index2 = this.activeCameras.indexOf(toRemove);
  16768. if (index2 !== -1) {
  16769. // Remove from the scene if mesh found
  16770. this.activeCameras.splice(index2, 1);
  16771. }
  16772. // Reset the activeCamera
  16773. if (this.activeCamera === toRemove) {
  16774. if (this.cameras.length > 0) {
  16775. this.activeCamera = this.cameras[0];
  16776. }
  16777. else {
  16778. this.activeCamera = null;
  16779. }
  16780. }
  16781. this.onCameraRemovedObservable.notifyObservers(toRemove);
  16782. return index;
  16783. };
  16784. Scene.prototype.addLight = function (newLight) {
  16785. newLight.uniqueId = this.getUniqueId();
  16786. this.lights.push(newLight);
  16787. this.sortLightsByPriority();
  16788. this.onNewLightAddedObservable.notifyObservers(newLight);
  16789. };
  16790. Scene.prototype.sortLightsByPriority = function () {
  16791. if (this.requireLightSorting) {
  16792. this.lights.sort(BABYLON.Light.compareLightsPriority);
  16793. }
  16794. };
  16795. Scene.prototype.addCamera = function (newCamera) {
  16796. newCamera.uniqueId = this.getUniqueId();
  16797. var position = this.cameras.push(newCamera);
  16798. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  16799. };
  16800. /**
  16801. * Switch active camera
  16802. * @param {Camera} newCamera - new active camera
  16803. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  16804. */
  16805. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  16806. if (attachControl === void 0) { attachControl = true; }
  16807. var canvas = this._engine.getRenderingCanvas();
  16808. this.activeCamera.detachControl(canvas);
  16809. this.activeCamera = newCamera;
  16810. if (attachControl) {
  16811. newCamera.attachControl(canvas);
  16812. }
  16813. };
  16814. /**
  16815. * sets the active camera of the scene using its ID
  16816. * @param {string} id - the camera's ID
  16817. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16818. * @see activeCamera
  16819. */
  16820. Scene.prototype.setActiveCameraByID = function (id) {
  16821. var camera = this.getCameraByID(id);
  16822. if (camera) {
  16823. this.activeCamera = camera;
  16824. return camera;
  16825. }
  16826. return null;
  16827. };
  16828. /**
  16829. * sets the active camera of the scene using its name
  16830. * @param {string} name - the camera's name
  16831. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16832. * @see activeCamera
  16833. */
  16834. Scene.prototype.setActiveCameraByName = function (name) {
  16835. var camera = this.getCameraByName(name);
  16836. if (camera) {
  16837. this.activeCamera = camera;
  16838. return camera;
  16839. }
  16840. return null;
  16841. };
  16842. /**
  16843. * get a material using its id
  16844. * @param {string} the material's ID
  16845. * @return {BABYLON.Material|null} the material or null if none found.
  16846. */
  16847. Scene.prototype.getMaterialByID = function (id) {
  16848. for (var index = 0; index < this.materials.length; index++) {
  16849. if (this.materials[index].id === id) {
  16850. return this.materials[index];
  16851. }
  16852. }
  16853. return null;
  16854. };
  16855. /**
  16856. * get a material using its name
  16857. * @param {string} the material's name
  16858. * @return {BABYLON.Material|null} the material or null if none found.
  16859. */
  16860. Scene.prototype.getMaterialByName = function (name) {
  16861. for (var index = 0; index < this.materials.length; index++) {
  16862. if (this.materials[index].name === name) {
  16863. return this.materials[index];
  16864. }
  16865. }
  16866. return null;
  16867. };
  16868. Scene.prototype.getLensFlareSystemByName = function (name) {
  16869. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16870. if (this.lensFlareSystems[index].name === name) {
  16871. return this.lensFlareSystems[index];
  16872. }
  16873. }
  16874. return null;
  16875. };
  16876. Scene.prototype.getLensFlareSystemByID = function (id) {
  16877. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16878. if (this.lensFlareSystems[index].id === id) {
  16879. return this.lensFlareSystems[index];
  16880. }
  16881. }
  16882. return null;
  16883. };
  16884. Scene.prototype.getCameraByID = function (id) {
  16885. for (var index = 0; index < this.cameras.length; index++) {
  16886. if (this.cameras[index].id === id) {
  16887. return this.cameras[index];
  16888. }
  16889. }
  16890. return null;
  16891. };
  16892. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  16893. for (var index = 0; index < this.cameras.length; index++) {
  16894. if (this.cameras[index].uniqueId === uniqueId) {
  16895. return this.cameras[index];
  16896. }
  16897. }
  16898. return null;
  16899. };
  16900. /**
  16901. * get a camera using its name
  16902. * @param {string} the camera's name
  16903. * @return {BABYLON.Camera|null} the camera or null if none found.
  16904. */
  16905. Scene.prototype.getCameraByName = function (name) {
  16906. for (var index = 0; index < this.cameras.length; index++) {
  16907. if (this.cameras[index].name === name) {
  16908. return this.cameras[index];
  16909. }
  16910. }
  16911. return null;
  16912. };
  16913. /**
  16914. * get a bone using its id
  16915. * @param {string} the bone's id
  16916. * @return {BABYLON.Bone|null} the bone or null if not found
  16917. */
  16918. Scene.prototype.getBoneByID = function (id) {
  16919. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16920. var skeleton = this.skeletons[skeletonIndex];
  16921. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16922. if (skeleton.bones[boneIndex].id === id) {
  16923. return skeleton.bones[boneIndex];
  16924. }
  16925. }
  16926. }
  16927. return null;
  16928. };
  16929. /**
  16930. * get a bone using its id
  16931. * @param {string} the bone's name
  16932. * @return {BABYLON.Bone|null} the bone or null if not found
  16933. */
  16934. Scene.prototype.getBoneByName = function (name) {
  16935. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16936. var skeleton = this.skeletons[skeletonIndex];
  16937. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16938. if (skeleton.bones[boneIndex].name === name) {
  16939. return skeleton.bones[boneIndex];
  16940. }
  16941. }
  16942. }
  16943. return null;
  16944. };
  16945. /**
  16946. * get a light node using its name
  16947. * @param {string} the light's name
  16948. * @return {BABYLON.Light|null} the light or null if none found.
  16949. */
  16950. Scene.prototype.getLightByName = function (name) {
  16951. for (var index = 0; index < this.lights.length; index++) {
  16952. if (this.lights[index].name === name) {
  16953. return this.lights[index];
  16954. }
  16955. }
  16956. return null;
  16957. };
  16958. /**
  16959. * get a light node using its ID
  16960. * @param {string} the light's id
  16961. * @return {BABYLON.Light|null} the light or null if none found.
  16962. */
  16963. Scene.prototype.getLightByID = function (id) {
  16964. for (var index = 0; index < this.lights.length; index++) {
  16965. if (this.lights[index].id === id) {
  16966. return this.lights[index];
  16967. }
  16968. }
  16969. return null;
  16970. };
  16971. /**
  16972. * get a light node using its scene-generated unique ID
  16973. * @param {number} the light's unique id
  16974. * @return {BABYLON.Light|null} the light or null if none found.
  16975. */
  16976. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  16977. for (var index = 0; index < this.lights.length; index++) {
  16978. if (this.lights[index].uniqueId === uniqueId) {
  16979. return this.lights[index];
  16980. }
  16981. }
  16982. return null;
  16983. };
  16984. /**
  16985. * get a particle system by id
  16986. * @param id {number} the particle system id
  16987. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  16988. */
  16989. Scene.prototype.getParticleSystemByID = function (id) {
  16990. for (var index = 0; index < this.particleSystems.length; index++) {
  16991. if (this.particleSystems[index].id === id) {
  16992. return this.particleSystems[index];
  16993. }
  16994. }
  16995. return null;
  16996. };
  16997. /**
  16998. * get a geometry using its ID
  16999. * @param {string} the geometry's id
  17000. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17001. */
  17002. Scene.prototype.getGeometryByID = function (id) {
  17003. for (var index = 0; index < this._geometries.length; index++) {
  17004. if (this._geometries[index].id === id) {
  17005. return this._geometries[index];
  17006. }
  17007. }
  17008. return null;
  17009. };
  17010. /**
  17011. * add a new geometry to this scene.
  17012. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17013. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17014. * @return {boolean} was the geometry added or not
  17015. */
  17016. Scene.prototype.pushGeometry = function (geometry, force) {
  17017. if (!force && this.getGeometryByID(geometry.id)) {
  17018. return false;
  17019. }
  17020. this._geometries.push(geometry);
  17021. //notify the collision coordinator
  17022. if (this.collisionCoordinator) {
  17023. this.collisionCoordinator.onGeometryAdded(geometry);
  17024. }
  17025. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17026. return true;
  17027. };
  17028. /**
  17029. * Removes an existing geometry
  17030. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17031. * @return {boolean} was the geometry removed or not
  17032. */
  17033. Scene.prototype.removeGeometry = function (geometry) {
  17034. var index = this._geometries.indexOf(geometry);
  17035. if (index > -1) {
  17036. this._geometries.splice(index, 1);
  17037. //notify the collision coordinator
  17038. if (this.collisionCoordinator) {
  17039. this.collisionCoordinator.onGeometryDeleted(geometry);
  17040. }
  17041. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17042. return true;
  17043. }
  17044. return false;
  17045. };
  17046. Scene.prototype.getGeometries = function () {
  17047. return this._geometries;
  17048. };
  17049. /**
  17050. * Get the first added mesh found of a given ID
  17051. * @param {string} id - the id to search for
  17052. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17053. */
  17054. Scene.prototype.getMeshByID = function (id) {
  17055. for (var index = 0; index < this.meshes.length; index++) {
  17056. if (this.meshes[index].id === id) {
  17057. return this.meshes[index];
  17058. }
  17059. }
  17060. return null;
  17061. };
  17062. Scene.prototype.getMeshesByID = function (id) {
  17063. return this.meshes.filter(function (m) {
  17064. return m.id === id;
  17065. });
  17066. };
  17067. /**
  17068. * Get a mesh with its auto-generated unique id
  17069. * @param {number} uniqueId - the unique id to search for
  17070. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17071. */
  17072. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  17073. for (var index = 0; index < this.meshes.length; index++) {
  17074. if (this.meshes[index].uniqueId === uniqueId) {
  17075. return this.meshes[index];
  17076. }
  17077. }
  17078. return null;
  17079. };
  17080. /**
  17081. * Get a the last added mesh found of a given ID
  17082. * @param {string} id - the id to search for
  17083. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17084. */
  17085. Scene.prototype.getLastMeshByID = function (id) {
  17086. for (var index = this.meshes.length - 1; index >= 0; index--) {
  17087. if (this.meshes[index].id === id) {
  17088. return this.meshes[index];
  17089. }
  17090. }
  17091. return null;
  17092. };
  17093. /**
  17094. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  17095. * @param {string} id - the id to search for
  17096. * @return {BABYLON.Node|null} the node found or null if not found at all.
  17097. */
  17098. Scene.prototype.getLastEntryByID = function (id) {
  17099. var index;
  17100. for (index = this.meshes.length - 1; index >= 0; index--) {
  17101. if (this.meshes[index].id === id) {
  17102. return this.meshes[index];
  17103. }
  17104. }
  17105. for (index = this.cameras.length - 1; index >= 0; index--) {
  17106. if (this.cameras[index].id === id) {
  17107. return this.cameras[index];
  17108. }
  17109. }
  17110. for (index = this.lights.length - 1; index >= 0; index--) {
  17111. if (this.lights[index].id === id) {
  17112. return this.lights[index];
  17113. }
  17114. }
  17115. return null;
  17116. };
  17117. Scene.prototype.getNodeByID = function (id) {
  17118. var mesh = this.getMeshByID(id);
  17119. if (mesh) {
  17120. return mesh;
  17121. }
  17122. var light = this.getLightByID(id);
  17123. if (light) {
  17124. return light;
  17125. }
  17126. var camera = this.getCameraByID(id);
  17127. if (camera) {
  17128. return camera;
  17129. }
  17130. var bone = this.getBoneByID(id);
  17131. return bone;
  17132. };
  17133. Scene.prototype.getNodeByName = function (name) {
  17134. var mesh = this.getMeshByName(name);
  17135. if (mesh) {
  17136. return mesh;
  17137. }
  17138. var light = this.getLightByName(name);
  17139. if (light) {
  17140. return light;
  17141. }
  17142. var camera = this.getCameraByName(name);
  17143. if (camera) {
  17144. return camera;
  17145. }
  17146. var bone = this.getBoneByName(name);
  17147. return bone;
  17148. };
  17149. Scene.prototype.getMeshByName = function (name) {
  17150. for (var index = 0; index < this.meshes.length; index++) {
  17151. if (this.meshes[index].name === name) {
  17152. return this.meshes[index];
  17153. }
  17154. }
  17155. return null;
  17156. };
  17157. Scene.prototype.getSoundByName = function (name) {
  17158. var index;
  17159. if (BABYLON.AudioEngine) {
  17160. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  17161. if (this.mainSoundTrack.soundCollection[index].name === name) {
  17162. return this.mainSoundTrack.soundCollection[index];
  17163. }
  17164. }
  17165. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  17166. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  17167. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  17168. return this.soundTracks[sdIndex].soundCollection[index];
  17169. }
  17170. }
  17171. }
  17172. }
  17173. return null;
  17174. };
  17175. Scene.prototype.getLastSkeletonByID = function (id) {
  17176. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  17177. if (this.skeletons[index].id === id) {
  17178. return this.skeletons[index];
  17179. }
  17180. }
  17181. return null;
  17182. };
  17183. Scene.prototype.getSkeletonById = function (id) {
  17184. for (var index = 0; index < this.skeletons.length; index++) {
  17185. if (this.skeletons[index].id === id) {
  17186. return this.skeletons[index];
  17187. }
  17188. }
  17189. return null;
  17190. };
  17191. Scene.prototype.getSkeletonByName = function (name) {
  17192. for (var index = 0; index < this.skeletons.length; index++) {
  17193. if (this.skeletons[index].name === name) {
  17194. return this.skeletons[index];
  17195. }
  17196. }
  17197. return null;
  17198. };
  17199. Scene.prototype.getMorphTargetManagerById = function (id) {
  17200. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  17201. if (this.morphTargetManagers[index].uniqueId === id) {
  17202. return this.morphTargetManagers[index];
  17203. }
  17204. }
  17205. return null;
  17206. };
  17207. Scene.prototype.isActiveMesh = function (mesh) {
  17208. return (this._activeMeshes.indexOf(mesh) !== -1);
  17209. };
  17210. /**
  17211. * Return a the first highlight layer of the scene with a given name.
  17212. * @param name The name of the highlight layer to look for.
  17213. * @return The highlight layer if found otherwise null.
  17214. */
  17215. Scene.prototype.getHighlightLayerByName = function (name) {
  17216. for (var index = 0; index < this.highlightLayers.length; index++) {
  17217. if (this.highlightLayers[index].name === name) {
  17218. return this.highlightLayers[index];
  17219. }
  17220. }
  17221. return null;
  17222. };
  17223. Object.defineProperty(Scene.prototype, "uid", {
  17224. /**
  17225. * Return a unique id as a string which can serve as an identifier for the scene
  17226. */
  17227. get: function () {
  17228. if (!this._uid) {
  17229. this._uid = BABYLON.Tools.RandomId();
  17230. }
  17231. return this._uid;
  17232. },
  17233. enumerable: true,
  17234. configurable: true
  17235. });
  17236. /**
  17237. * Add an externaly attached data from its key.
  17238. * This method call will fail and return false, if such key already exists.
  17239. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17240. * @param key the unique key that identifies the data
  17241. * @param data the data object to associate to the key for this Engine instance
  17242. * @return true if no such key were already present and the data was added successfully, false otherwise
  17243. */
  17244. Scene.prototype.addExternalData = function (key, data) {
  17245. if (!this._externalData) {
  17246. this._externalData = new BABYLON.StringDictionary();
  17247. }
  17248. return this._externalData.add(key, data);
  17249. };
  17250. /**
  17251. * Get an externaly attached data from its key
  17252. * @param key the unique key that identifies the data
  17253. * @return the associated data, if present (can be null), or undefined if not present
  17254. */
  17255. Scene.prototype.getExternalData = function (key) {
  17256. if (!this._externalData) {
  17257. return null;
  17258. }
  17259. return this._externalData.get(key);
  17260. };
  17261. /**
  17262. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17263. * @param key the unique key that identifies the data
  17264. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17265. * @return the associated data, can be null if the factory returned null.
  17266. */
  17267. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17268. if (!this._externalData) {
  17269. this._externalData = new BABYLON.StringDictionary();
  17270. }
  17271. return this._externalData.getOrAddWithFactory(key, factory);
  17272. };
  17273. /**
  17274. * Remove an externaly attached data from the Engine instance
  17275. * @param key the unique key that identifies the data
  17276. * @return true if the data was successfully removed, false if it doesn't exist
  17277. */
  17278. Scene.prototype.removeExternalData = function (key) {
  17279. return this._externalData.remove(key);
  17280. };
  17281. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  17282. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  17283. var material = subMesh.getMaterial();
  17284. if (mesh.showSubMeshesBoundingBox) {
  17285. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  17286. }
  17287. if (material) {
  17288. // Render targets
  17289. if (material.getRenderTargetTextures) {
  17290. if (this._processedMaterials.indexOf(material) === -1) {
  17291. this._processedMaterials.push(material);
  17292. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  17293. }
  17294. }
  17295. // Dispatch
  17296. this._activeIndices.addCount(subMesh.indexCount, false);
  17297. this._renderingManager.dispatch(subMesh);
  17298. }
  17299. }
  17300. };
  17301. Scene.prototype._isInIntermediateRendering = function () {
  17302. return this._intermediateRendering;
  17303. };
  17304. Scene.prototype._evaluateActiveMeshes = function () {
  17305. this.activeCamera._activeMeshes.reset();
  17306. this._activeMeshes.reset();
  17307. this._renderingManager.reset();
  17308. this._processedMaterials.reset();
  17309. this._activeParticleSystems.reset();
  17310. this._activeSkeletons.reset();
  17311. this._softwareSkinnedMeshes.reset();
  17312. if (this._boundingBoxRenderer) {
  17313. this._boundingBoxRenderer.reset();
  17314. }
  17315. // Meshes
  17316. var meshes;
  17317. var len;
  17318. if (this._selectionOctree) {
  17319. var selection = this._selectionOctree.select(this._frustumPlanes);
  17320. meshes = selection.data;
  17321. len = selection.length;
  17322. }
  17323. else {
  17324. len = this.meshes.length;
  17325. meshes = this.meshes;
  17326. }
  17327. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  17328. var mesh = meshes[meshIndex];
  17329. if (mesh.isBlocked) {
  17330. continue;
  17331. }
  17332. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  17333. if (!mesh.isReady() || !mesh.isEnabled()) {
  17334. continue;
  17335. }
  17336. mesh.computeWorldMatrix();
  17337. // Intersections
  17338. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  17339. this._meshesForIntersections.pushNoDuplicate(mesh);
  17340. }
  17341. // Switch to current LOD
  17342. var meshLOD = mesh.getLOD(this.activeCamera);
  17343. if (!meshLOD) {
  17344. continue;
  17345. }
  17346. mesh._preActivate();
  17347. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  17348. this._activeMeshes.push(mesh);
  17349. this.activeCamera._activeMeshes.push(mesh);
  17350. mesh._activate(this._renderId);
  17351. this._activeMesh(mesh, meshLOD);
  17352. }
  17353. }
  17354. // Particle systems
  17355. this._particlesDuration.beginMonitoring();
  17356. var beforeParticlesDate = BABYLON.Tools.Now;
  17357. if (this.particlesEnabled) {
  17358. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  17359. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  17360. var particleSystem = this.particleSystems[particleIndex];
  17361. if (!particleSystem.isStarted()) {
  17362. continue;
  17363. }
  17364. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  17365. this._activeParticleSystems.push(particleSystem);
  17366. particleSystem.animate();
  17367. this._renderingManager.dispatchParticles(particleSystem);
  17368. }
  17369. }
  17370. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  17371. }
  17372. this._particlesDuration.endMonitoring(false);
  17373. };
  17374. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  17375. if (mesh.skeleton && this.skeletonsEnabled) {
  17376. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  17377. mesh.skeleton.prepare();
  17378. }
  17379. if (!mesh.computeBonesUsingShaders) {
  17380. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  17381. }
  17382. }
  17383. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  17384. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  17385. }
  17386. if (mesh && mesh.subMeshes) {
  17387. // Submeshes Octrees
  17388. var len;
  17389. var subMeshes;
  17390. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  17391. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  17392. len = intersections.length;
  17393. subMeshes = intersections.data;
  17394. }
  17395. else {
  17396. subMeshes = mesh.subMeshes;
  17397. len = subMeshes.length;
  17398. }
  17399. for (var subIndex = 0; subIndex < len; subIndex++) {
  17400. var subMesh = subMeshes[subIndex];
  17401. this._evaluateSubMesh(subMesh, mesh);
  17402. }
  17403. }
  17404. };
  17405. Scene.prototype.updateTransformMatrix = function (force) {
  17406. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  17407. };
  17408. Scene.prototype._renderForCamera = function (camera) {
  17409. var engine = this._engine;
  17410. var startTime = BABYLON.Tools.Now;
  17411. this.activeCamera = camera;
  17412. if (!this.activeCamera)
  17413. throw new Error("Active camera not set");
  17414. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17415. // Viewport
  17416. engine.setViewport(this.activeCamera.viewport);
  17417. // Camera
  17418. this.resetCachedMaterial();
  17419. this._renderId++;
  17420. this.updateTransformMatrix();
  17421. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  17422. // Meshes
  17423. this._evaluateActiveMeshesDuration.beginMonitoring();
  17424. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  17425. this._evaluateActiveMeshes();
  17426. this._evaluateActiveMeshesDuration.endMonitoring(false);
  17427. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  17428. // Software skinning
  17429. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  17430. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  17431. mesh.applySkeleton(mesh.skeleton);
  17432. }
  17433. // Render targets
  17434. this._renderTargetsDuration.beginMonitoring();
  17435. var needsRestoreFrameBuffer = false;
  17436. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17437. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  17438. this._intermediateRendering = true;
  17439. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17440. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  17441. var renderTarget = this._renderTargets.data[renderIndex];
  17442. if (renderTarget._shouldRender()) {
  17443. this._renderId++;
  17444. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  17445. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  17446. }
  17447. }
  17448. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17449. this._intermediateRendering = false;
  17450. this._renderId++;
  17451. needsRestoreFrameBuffer = true; // Restore back buffer
  17452. }
  17453. // Render HighlightLayer Texture
  17454. var stencilState = this._engine.getStencilBuffer();
  17455. var renderhighlights = false;
  17456. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  17457. this._intermediateRendering = true;
  17458. for (var i = 0; i < this.highlightLayers.length; i++) {
  17459. var highlightLayer = this.highlightLayers[i];
  17460. if (highlightLayer.shouldRender() &&
  17461. (!highlightLayer.camera ||
  17462. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  17463. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  17464. renderhighlights = true;
  17465. var renderTarget = highlightLayer._mainTexture;
  17466. if (renderTarget._shouldRender()) {
  17467. this._renderId++;
  17468. renderTarget.render(false, false);
  17469. needsRestoreFrameBuffer = true;
  17470. }
  17471. }
  17472. }
  17473. this._intermediateRendering = false;
  17474. this._renderId++;
  17475. }
  17476. if (needsRestoreFrameBuffer) {
  17477. engine.restoreDefaultFramebuffer(); // Restore back buffer
  17478. }
  17479. this._renderTargetsDuration.endMonitoring(false);
  17480. // Prepare Frame
  17481. this.postProcessManager._prepareFrame();
  17482. this._renderDuration.beginMonitoring();
  17483. // Backgrounds
  17484. var layerIndex;
  17485. var layer;
  17486. if (this.layers.length) {
  17487. engine.setDepthBuffer(false);
  17488. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17489. layer = this.layers[layerIndex];
  17490. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  17491. layer.render();
  17492. }
  17493. }
  17494. engine.setDepthBuffer(true);
  17495. }
  17496. // Render
  17497. BABYLON.Tools.StartPerformanceCounter("Main render");
  17498. // Activate HighlightLayer stencil
  17499. if (renderhighlights) {
  17500. this._engine.setStencilBuffer(true);
  17501. }
  17502. this._renderingManager.render(null, null, true, true);
  17503. // Restore HighlightLayer stencil
  17504. if (renderhighlights) {
  17505. this._engine.setStencilBuffer(stencilState);
  17506. }
  17507. BABYLON.Tools.EndPerformanceCounter("Main render");
  17508. // Bounding boxes
  17509. if (this._boundingBoxRenderer) {
  17510. this._boundingBoxRenderer.render();
  17511. }
  17512. // Lens flares
  17513. if (this.lensFlaresEnabled) {
  17514. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17515. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  17516. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  17517. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  17518. lensFlareSystem.render();
  17519. }
  17520. }
  17521. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17522. }
  17523. // Foregrounds
  17524. if (this.layers.length) {
  17525. engine.setDepthBuffer(false);
  17526. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17527. layer = this.layers[layerIndex];
  17528. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  17529. layer.render();
  17530. }
  17531. }
  17532. engine.setDepthBuffer(true);
  17533. }
  17534. // Highlight Layer
  17535. if (renderhighlights) {
  17536. engine.setDepthBuffer(false);
  17537. for (var i = 0; i < this.highlightLayers.length; i++) {
  17538. if (this.highlightLayers[i].shouldRender()) {
  17539. this.highlightLayers[i].render();
  17540. }
  17541. }
  17542. engine.setDepthBuffer(true);
  17543. }
  17544. this._renderDuration.endMonitoring(false);
  17545. // Finalize frame
  17546. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  17547. // Update camera
  17548. this.activeCamera._updateFromScene();
  17549. // Reset some special arrays
  17550. this._renderTargets.reset();
  17551. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  17552. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17553. };
  17554. Scene.prototype._processSubCameras = function (camera) {
  17555. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  17556. this._renderForCamera(camera);
  17557. return;
  17558. }
  17559. // rig cameras
  17560. for (var index = 0; index < camera._rigCameras.length; index++) {
  17561. this._renderForCamera(camera._rigCameras[index]);
  17562. }
  17563. this.activeCamera = camera;
  17564. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  17565. // Update camera
  17566. this.activeCamera._updateFromScene();
  17567. };
  17568. Scene.prototype._checkIntersections = function () {
  17569. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  17570. var sourceMesh = this._meshesForIntersections.data[index];
  17571. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  17572. var action = sourceMesh.actionManager.actions[actionIndex];
  17573. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17574. var parameters = action.getTriggerParameter();
  17575. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  17576. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  17577. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  17578. if (areIntersecting && currentIntersectionInProgress === -1) {
  17579. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  17580. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17581. sourceMesh._intersectionsInProgress.push(otherMesh);
  17582. }
  17583. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17584. sourceMesh._intersectionsInProgress.push(otherMesh);
  17585. }
  17586. }
  17587. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  17588. //They intersected, and now they don't.
  17589. //is this trigger an exit trigger? execute an event.
  17590. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17591. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17592. }
  17593. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  17594. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17595. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  17596. }
  17597. }
  17598. }
  17599. }
  17600. }
  17601. };
  17602. Scene.prototype.render = function () {
  17603. if (this.isDisposed) {
  17604. return;
  17605. }
  17606. this._lastFrameDuration.beginMonitoring();
  17607. this._particlesDuration.fetchNewFrame();
  17608. this._spritesDuration.fetchNewFrame();
  17609. this._activeParticles.fetchNewFrame();
  17610. this._renderDuration.fetchNewFrame();
  17611. this._renderTargetsDuration.fetchNewFrame();
  17612. this._evaluateActiveMeshesDuration.fetchNewFrame();
  17613. this._totalVertices.fetchNewFrame();
  17614. this._activeIndices.fetchNewFrame();
  17615. this._activeBones.fetchNewFrame();
  17616. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  17617. this._meshesForIntersections.reset();
  17618. this.resetCachedMaterial();
  17619. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  17620. // Actions
  17621. if (this.actionManager) {
  17622. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  17623. }
  17624. //Simplification Queue
  17625. if (this.simplificationQueue && !this.simplificationQueue.running) {
  17626. this.simplificationQueue.executeNext();
  17627. }
  17628. // Animations
  17629. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  17630. this._animationRatio = deltaTime * (60.0 / 1000.0);
  17631. this._animate();
  17632. // Physics
  17633. if (this._physicsEngine) {
  17634. BABYLON.Tools.StartPerformanceCounter("Physics");
  17635. this._physicsEngine._step(deltaTime / 1000.0);
  17636. BABYLON.Tools.EndPerformanceCounter("Physics");
  17637. }
  17638. // Before render
  17639. this.onBeforeRenderObservable.notifyObservers(this);
  17640. // Customs render targets
  17641. this._renderTargetsDuration.beginMonitoring();
  17642. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17643. var engine = this.getEngine();
  17644. var currentActiveCamera = this.activeCamera;
  17645. if (this.renderTargetsEnabled) {
  17646. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17647. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  17648. var renderTarget = this.customRenderTargets[customIndex];
  17649. if (renderTarget._shouldRender()) {
  17650. this._renderId++;
  17651. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  17652. if (!this.activeCamera)
  17653. throw new Error("Active camera not set");
  17654. // Viewport
  17655. engine.setViewport(this.activeCamera.viewport);
  17656. // Camera
  17657. this.updateTransformMatrix();
  17658. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  17659. }
  17660. }
  17661. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17662. this._renderId++;
  17663. }
  17664. // Restore back buffer
  17665. if (this.customRenderTargets.length > 0) {
  17666. engine.restoreDefaultFramebuffer();
  17667. }
  17668. this._renderTargetsDuration.endMonitoring();
  17669. this.activeCamera = currentActiveCamera;
  17670. // Procedural textures
  17671. if (this.proceduralTexturesEnabled) {
  17672. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17673. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  17674. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  17675. if (proceduralTexture._shouldRender()) {
  17676. proceduralTexture.render();
  17677. }
  17678. }
  17679. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17680. }
  17681. // Clear
  17682. if (this.autoClearDepthAndStencil || this.autoClear) {
  17683. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  17684. }
  17685. // Shadows
  17686. if (this.shadowsEnabled) {
  17687. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  17688. var light = this.lights[lightIndex];
  17689. var shadowGenerator = light.getShadowGenerator();
  17690. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  17691. var shadowMap = shadowGenerator.getShadowMap();
  17692. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  17693. this._renderTargets.push(shadowMap);
  17694. }
  17695. }
  17696. }
  17697. }
  17698. // Depth renderer
  17699. if (this._depthRenderer) {
  17700. this._renderTargets.push(this._depthRenderer.getDepthMap());
  17701. }
  17702. // Geometry renderer
  17703. if (this._geometryBufferRenderer) {
  17704. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  17705. }
  17706. // RenderPipeline
  17707. if (this._postProcessRenderPipelineManager) {
  17708. this._postProcessRenderPipelineManager.update();
  17709. }
  17710. // Multi-cameras?
  17711. if (this.activeCameras.length > 0) {
  17712. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  17713. if (cameraIndex > 0) {
  17714. this._engine.clear(null, false, true, true);
  17715. }
  17716. this._processSubCameras(this.activeCameras[cameraIndex]);
  17717. }
  17718. }
  17719. else {
  17720. if (!this.activeCamera) {
  17721. throw new Error("No camera defined");
  17722. }
  17723. this._processSubCameras(this.activeCamera);
  17724. }
  17725. // Intersection checks
  17726. this._checkIntersections();
  17727. // Update the audio listener attached to the camera
  17728. if (BABYLON.AudioEngine) {
  17729. this._updateAudioParameters();
  17730. }
  17731. // After render
  17732. if (this.afterRender) {
  17733. this.afterRender();
  17734. }
  17735. this.onAfterRenderObservable.notifyObservers(this);
  17736. // Cleaning
  17737. for (var index = 0; index < this._toBeDisposed.length; index++) {
  17738. this._toBeDisposed.data[index].dispose();
  17739. this._toBeDisposed[index] = null;
  17740. }
  17741. this._toBeDisposed.reset();
  17742. if (this.dumpNextRenderTargets) {
  17743. this.dumpNextRenderTargets = false;
  17744. }
  17745. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  17746. this._lastFrameDuration.endMonitoring();
  17747. this._totalMeshesCounter.addCount(this.meshes.length, true);
  17748. this._totalLightsCounter.addCount(this.lights.length, true);
  17749. this._totalMaterialsCounter.addCount(this.materials.length, true);
  17750. this._totalTexturesCounter.addCount(this.textures.length, true);
  17751. this._activeBones.addCount(0, true);
  17752. this._activeIndices.addCount(0, true);
  17753. this._activeParticles.addCount(0, true);
  17754. };
  17755. Scene.prototype._updateAudioParameters = function () {
  17756. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  17757. return;
  17758. }
  17759. var listeningCamera;
  17760. var audioEngine = BABYLON.Engine.audioEngine;
  17761. if (this.activeCameras.length > 0) {
  17762. listeningCamera = this.activeCameras[0];
  17763. }
  17764. else {
  17765. listeningCamera = this.activeCamera;
  17766. }
  17767. if (listeningCamera && audioEngine.canUseWebAudio) {
  17768. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  17769. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  17770. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  17771. cameraDirection.normalize();
  17772. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  17773. var i;
  17774. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17775. var sound = this.mainSoundTrack.soundCollection[i];
  17776. if (sound.useCustomAttenuation) {
  17777. sound.updateDistanceFromListener();
  17778. }
  17779. }
  17780. for (i = 0; i < this.soundTracks.length; i++) {
  17781. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17782. sound = this.soundTracks[i].soundCollection[j];
  17783. if (sound.useCustomAttenuation) {
  17784. sound.updateDistanceFromListener();
  17785. }
  17786. }
  17787. }
  17788. }
  17789. };
  17790. Object.defineProperty(Scene.prototype, "audioEnabled", {
  17791. // Audio
  17792. get: function () {
  17793. return this._audioEnabled;
  17794. },
  17795. set: function (value) {
  17796. this._audioEnabled = value;
  17797. if (BABYLON.AudioEngine) {
  17798. if (this._audioEnabled) {
  17799. this._enableAudio();
  17800. }
  17801. else {
  17802. this._disableAudio();
  17803. }
  17804. }
  17805. },
  17806. enumerable: true,
  17807. configurable: true
  17808. });
  17809. Scene.prototype._disableAudio = function () {
  17810. var i;
  17811. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17812. this.mainSoundTrack.soundCollection[i].pause();
  17813. }
  17814. for (i = 0; i < this.soundTracks.length; i++) {
  17815. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17816. this.soundTracks[i].soundCollection[j].pause();
  17817. }
  17818. }
  17819. };
  17820. Scene.prototype._enableAudio = function () {
  17821. var i;
  17822. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17823. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  17824. this.mainSoundTrack.soundCollection[i].play();
  17825. }
  17826. }
  17827. for (i = 0; i < this.soundTracks.length; i++) {
  17828. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17829. if (this.soundTracks[i].soundCollection[j].isPaused) {
  17830. this.soundTracks[i].soundCollection[j].play();
  17831. }
  17832. }
  17833. }
  17834. };
  17835. Object.defineProperty(Scene.prototype, "headphone", {
  17836. get: function () {
  17837. return this._headphone;
  17838. },
  17839. set: function (value) {
  17840. this._headphone = value;
  17841. if (BABYLON.AudioEngine) {
  17842. if (this._headphone) {
  17843. this._switchAudioModeForHeadphones();
  17844. }
  17845. else {
  17846. this._switchAudioModeForNormalSpeakers();
  17847. }
  17848. }
  17849. },
  17850. enumerable: true,
  17851. configurable: true
  17852. });
  17853. Scene.prototype._switchAudioModeForHeadphones = function () {
  17854. this.mainSoundTrack.switchPanningModelToHRTF();
  17855. for (var i = 0; i < this.soundTracks.length; i++) {
  17856. this.soundTracks[i].switchPanningModelToHRTF();
  17857. }
  17858. };
  17859. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  17860. this.mainSoundTrack.switchPanningModelToEqualPower();
  17861. for (var i = 0; i < this.soundTracks.length; i++) {
  17862. this.soundTracks[i].switchPanningModelToEqualPower();
  17863. }
  17864. };
  17865. Scene.prototype.enableDepthRenderer = function () {
  17866. if (this._depthRenderer) {
  17867. return this._depthRenderer;
  17868. }
  17869. this._depthRenderer = new BABYLON.DepthRenderer(this);
  17870. return this._depthRenderer;
  17871. };
  17872. Scene.prototype.disableDepthRenderer = function () {
  17873. if (!this._depthRenderer) {
  17874. return;
  17875. }
  17876. this._depthRenderer.dispose();
  17877. this._depthRenderer = null;
  17878. };
  17879. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  17880. if (ratio === void 0) { ratio = 1; }
  17881. if (this._geometryBufferRenderer) {
  17882. return this._geometryBufferRenderer;
  17883. }
  17884. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  17885. if (!this._geometryBufferRenderer.isSupported) {
  17886. this._geometryBufferRenderer = null;
  17887. }
  17888. return this._geometryBufferRenderer;
  17889. };
  17890. Scene.prototype.disableGeometryBufferRenderer = function () {
  17891. if (!this._geometryBufferRenderer) {
  17892. return;
  17893. }
  17894. this._geometryBufferRenderer.dispose();
  17895. this._geometryBufferRenderer = null;
  17896. };
  17897. Scene.prototype.freezeMaterials = function () {
  17898. for (var i = 0; i < this.materials.length; i++) {
  17899. this.materials[i].freeze();
  17900. }
  17901. };
  17902. Scene.prototype.unfreezeMaterials = function () {
  17903. for (var i = 0; i < this.materials.length; i++) {
  17904. this.materials[i].unfreeze();
  17905. }
  17906. };
  17907. Scene.prototype.dispose = function () {
  17908. this.beforeRender = null;
  17909. this.afterRender = null;
  17910. this.skeletons = [];
  17911. this.morphTargetManagers = [];
  17912. this.importedMeshesFiles = new Array();
  17913. if (this._depthRenderer) {
  17914. this._depthRenderer.dispose();
  17915. }
  17916. // Smart arrays
  17917. if (this.activeCamera) {
  17918. this.activeCamera._activeMeshes.dispose();
  17919. this.activeCamera = null;
  17920. }
  17921. this._activeMeshes.dispose();
  17922. this._renderingManager.dispose();
  17923. this._processedMaterials.dispose();
  17924. this._activeParticleSystems.dispose();
  17925. this._activeSkeletons.dispose();
  17926. this._softwareSkinnedMeshes.dispose();
  17927. if (this._boundingBoxRenderer) {
  17928. this._boundingBoxRenderer.dispose();
  17929. }
  17930. this._meshesForIntersections.dispose();
  17931. this._toBeDisposed.dispose();
  17932. // Debug layer
  17933. if (this._debugLayer) {
  17934. this._debugLayer.hide();
  17935. }
  17936. // Events
  17937. this.onDisposeObservable.notifyObservers(this);
  17938. this.onDisposeObservable.clear();
  17939. this.onBeforeRenderObservable.clear();
  17940. this.onAfterRenderObservable.clear();
  17941. this.detachControl();
  17942. // Release sounds & sounds tracks
  17943. if (BABYLON.AudioEngine) {
  17944. this.disposeSounds();
  17945. }
  17946. // Detach cameras
  17947. var canvas = this._engine.getRenderingCanvas();
  17948. var index;
  17949. for (index = 0; index < this.cameras.length; index++) {
  17950. this.cameras[index].detachControl(canvas);
  17951. }
  17952. // Release lights
  17953. while (this.lights.length) {
  17954. this.lights[0].dispose();
  17955. }
  17956. // Release meshes
  17957. while (this.meshes.length) {
  17958. this.meshes[0].dispose(true);
  17959. }
  17960. // Release cameras
  17961. while (this.cameras.length) {
  17962. this.cameras[0].dispose();
  17963. }
  17964. // Release materials
  17965. while (this.materials.length) {
  17966. this.materials[0].dispose();
  17967. }
  17968. // Release particles
  17969. while (this.particleSystems.length) {
  17970. this.particleSystems[0].dispose();
  17971. }
  17972. // Release sprites
  17973. while (this.spriteManagers.length) {
  17974. this.spriteManagers[0].dispose();
  17975. }
  17976. // Release layers
  17977. while (this.layers.length) {
  17978. this.layers[0].dispose();
  17979. }
  17980. while (this.highlightLayers.length) {
  17981. this.highlightLayers[0].dispose();
  17982. }
  17983. // Release textures
  17984. while (this.textures.length) {
  17985. this.textures[0].dispose();
  17986. }
  17987. // Release UBO
  17988. this._sceneUbo.dispose();
  17989. // Post-processes
  17990. this.postProcessManager.dispose();
  17991. // Physics
  17992. if (this._physicsEngine) {
  17993. this.disablePhysicsEngine();
  17994. }
  17995. // Remove from engine
  17996. index = this._engine.scenes.indexOf(this);
  17997. if (index > -1) {
  17998. this._engine.scenes.splice(index, 1);
  17999. }
  18000. this._engine.wipeCaches();
  18001. this._engine = null;
  18002. };
  18003. Object.defineProperty(Scene.prototype, "isDisposed", {
  18004. get: function () {
  18005. return !this._engine;
  18006. },
  18007. enumerable: true,
  18008. configurable: true
  18009. });
  18010. // Release sounds & sounds tracks
  18011. Scene.prototype.disposeSounds = function () {
  18012. this.mainSoundTrack.dispose();
  18013. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  18014. this.soundTracks[scIndex].dispose();
  18015. }
  18016. };
  18017. // Octrees
  18018. Scene.prototype.getWorldExtends = function () {
  18019. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18020. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18021. for (var index = 0; index < this.meshes.length; index++) {
  18022. var mesh = this.meshes[index];
  18023. mesh.computeWorldMatrix(true);
  18024. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  18025. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  18026. BABYLON.Tools.CheckExtends(minBox, min, max);
  18027. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18028. }
  18029. return {
  18030. min: min,
  18031. max: max
  18032. };
  18033. };
  18034. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  18035. if (maxCapacity === void 0) { maxCapacity = 64; }
  18036. if (maxDepth === void 0) { maxDepth = 2; }
  18037. if (!this._selectionOctree) {
  18038. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  18039. }
  18040. var worldExtends = this.getWorldExtends();
  18041. // Update octree
  18042. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  18043. return this._selectionOctree;
  18044. };
  18045. // Picking
  18046. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  18047. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  18048. var engine = this._engine;
  18049. if (!camera) {
  18050. if (!this.activeCamera)
  18051. throw new Error("Active camera not set");
  18052. camera = this.activeCamera;
  18053. }
  18054. var cameraViewport = camera.viewport;
  18055. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18056. // Moving coordinates to local viewport world
  18057. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18058. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18059. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  18060. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  18061. };
  18062. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  18063. if (!BABYLON.PickingInfo) {
  18064. return null;
  18065. }
  18066. var engine = this._engine;
  18067. if (!camera) {
  18068. if (!this.activeCamera)
  18069. throw new Error("Active camera not set");
  18070. camera = this.activeCamera;
  18071. }
  18072. var cameraViewport = camera.viewport;
  18073. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18074. var identity = BABYLON.Matrix.Identity();
  18075. // Moving coordinates to local viewport world
  18076. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18077. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18078. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  18079. };
  18080. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  18081. if (!BABYLON.PickingInfo) {
  18082. return null;
  18083. }
  18084. var pickingInfo = null;
  18085. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18086. var mesh = this.meshes[meshIndex];
  18087. if (predicate) {
  18088. if (!predicate(mesh)) {
  18089. continue;
  18090. }
  18091. }
  18092. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18093. continue;
  18094. }
  18095. var world = mesh.getWorldMatrix();
  18096. var ray = rayFunction(world);
  18097. var result = mesh.intersects(ray, fastCheck);
  18098. if (!result || !result.hit)
  18099. continue;
  18100. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18101. continue;
  18102. pickingInfo = result;
  18103. if (fastCheck) {
  18104. break;
  18105. }
  18106. }
  18107. return pickingInfo || new BABYLON.PickingInfo();
  18108. };
  18109. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  18110. if (!BABYLON.PickingInfo) {
  18111. return null;
  18112. }
  18113. var pickingInfos = new Array();
  18114. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18115. var mesh = this.meshes[meshIndex];
  18116. if (predicate) {
  18117. if (!predicate(mesh)) {
  18118. continue;
  18119. }
  18120. }
  18121. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18122. continue;
  18123. }
  18124. var world = mesh.getWorldMatrix();
  18125. var ray = rayFunction(world);
  18126. var result = mesh.intersects(ray, false);
  18127. if (!result || !result.hit)
  18128. continue;
  18129. pickingInfos.push(result);
  18130. }
  18131. return pickingInfos;
  18132. };
  18133. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  18134. if (!BABYLON.PickingInfo) {
  18135. return null;
  18136. }
  18137. var pickingInfo = null;
  18138. camera = camera || this.activeCamera;
  18139. if (this.spriteManagers.length > 0) {
  18140. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18141. var spriteManager = this.spriteManagers[spriteIndex];
  18142. if (!spriteManager.isPickable) {
  18143. continue;
  18144. }
  18145. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18146. if (!result || !result.hit)
  18147. continue;
  18148. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18149. continue;
  18150. pickingInfo = result;
  18151. if (fastCheck) {
  18152. break;
  18153. }
  18154. }
  18155. }
  18156. return pickingInfo || new BABYLON.PickingInfo();
  18157. };
  18158. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18159. /// <param name="x">X position on screen</param>
  18160. /// <param name="y">Y position on screen</param>
  18161. /// <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>
  18162. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18163. /// <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>
  18164. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  18165. var _this = this;
  18166. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  18167. };
  18168. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18169. /// <param name="x">X position on screen</param>
  18170. /// <param name="y">Y position on screen</param>
  18171. /// <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>
  18172. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18173. /// <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>
  18174. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  18175. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  18176. };
  18177. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  18178. var _this = this;
  18179. return this._internalPick(function (world) {
  18180. if (!_this._pickWithRayInverseMatrix) {
  18181. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18182. }
  18183. world.invertToRef(_this._pickWithRayInverseMatrix);
  18184. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18185. }, predicate, fastCheck);
  18186. };
  18187. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18188. /// <param name="x">X position on screen</param>
  18189. /// <param name="y">Y position on screen</param>
  18190. /// <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>
  18191. /// <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>
  18192. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  18193. var _this = this;
  18194. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  18195. };
  18196. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18197. /// <param name="ray">Ray to use</param>
  18198. /// <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>
  18199. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  18200. var _this = this;
  18201. return this._internalMultiPick(function (world) {
  18202. if (!_this._pickWithRayInverseMatrix) {
  18203. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18204. }
  18205. world.invertToRef(_this._pickWithRayInverseMatrix);
  18206. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18207. }, predicate);
  18208. };
  18209. Scene.prototype.setPointerOverMesh = function (mesh) {
  18210. if (this._pointerOverMesh === mesh) {
  18211. return;
  18212. }
  18213. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18214. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18215. }
  18216. this._pointerOverMesh = mesh;
  18217. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18218. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18219. }
  18220. };
  18221. Scene.prototype.getPointerOverMesh = function () {
  18222. return this._pointerOverMesh;
  18223. };
  18224. Scene.prototype.setPointerOverSprite = function (sprite) {
  18225. if (this._pointerOverSprite === sprite) {
  18226. return;
  18227. }
  18228. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18229. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18230. }
  18231. this._pointerOverSprite = sprite;
  18232. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18233. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18234. }
  18235. };
  18236. Scene.prototype.getPointerOverSprite = function () {
  18237. return this._pointerOverSprite;
  18238. };
  18239. // Physics
  18240. Scene.prototype.getPhysicsEngine = function () {
  18241. return this._physicsEngine;
  18242. };
  18243. /**
  18244. * Enables physics to the current scene
  18245. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  18246. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  18247. * @return {boolean} was the physics engine initialized
  18248. */
  18249. Scene.prototype.enablePhysics = function (gravity, plugin) {
  18250. if (this._physicsEngine) {
  18251. return true;
  18252. }
  18253. try {
  18254. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  18255. return true;
  18256. }
  18257. catch (e) {
  18258. BABYLON.Tools.Error(e.message);
  18259. return false;
  18260. }
  18261. };
  18262. Scene.prototype.disablePhysicsEngine = function () {
  18263. if (!this._physicsEngine) {
  18264. return;
  18265. }
  18266. this._physicsEngine.dispose();
  18267. this._physicsEngine = undefined;
  18268. };
  18269. Scene.prototype.isPhysicsEnabled = function () {
  18270. return this._physicsEngine !== undefined;
  18271. };
  18272. Scene.prototype.deleteCompoundImpostor = function (compound) {
  18273. var mesh = compound.parts[0].mesh;
  18274. mesh.physicsImpostor.dispose();
  18275. mesh.physicsImpostor = null;
  18276. };
  18277. // Misc.
  18278. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  18279. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  18280. // Light
  18281. if (this.lights.length === 0) {
  18282. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  18283. }
  18284. // Camera
  18285. if (!this.activeCamera) {
  18286. var worldExtends = this.getWorldExtends();
  18287. var worldSize = worldExtends.max.subtract(worldExtends.min);
  18288. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  18289. var camera;
  18290. var radius = worldSize.length() * 1.5;
  18291. if (createArcRotateCamera) {
  18292. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", 4.712, 1.571, radius, worldCenter, this);
  18293. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  18294. arcRotateCamera.wheelPrecision = 100 / radius;
  18295. camera = arcRotateCamera;
  18296. }
  18297. else {
  18298. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, this.useRightHandedSystem ? -radius : radius), this);
  18299. freeCamera.setTarget(worldCenter);
  18300. camera = freeCamera;
  18301. }
  18302. camera.minZ = radius * 0.01;
  18303. camera.maxZ = radius * 100;
  18304. camera.speed = radius * 0.2;
  18305. this.activeCamera = camera;
  18306. }
  18307. };
  18308. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr) {
  18309. if (pbr === void 0) { pbr = false; }
  18310. if (environmentTexture) {
  18311. this.environmentTexture = environmentTexture;
  18312. }
  18313. if (!this.environmentTexture) {
  18314. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  18315. return;
  18316. }
  18317. if (!this.environmentTexture) {
  18318. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  18319. return;
  18320. }
  18321. // Skybox
  18322. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", 1000.0, this);
  18323. if (pbr) {
  18324. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  18325. hdrSkyboxMaterial.backFaceCulling = false;
  18326. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  18327. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  18328. hdrSkyboxMaterial.microSurface = 1.0;
  18329. hdrSkyboxMaterial.disableLighting = true;
  18330. hdrSkybox.infiniteDistance = true;
  18331. hdrSkybox.material = hdrSkyboxMaterial;
  18332. }
  18333. else {
  18334. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  18335. skyboxMaterial.backFaceCulling = false;
  18336. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  18337. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  18338. skyboxMaterial.diffuseColor = new BABYLON.Color3(0, 0, 0);
  18339. skyboxMaterial.specularColor = new BABYLON.Color3(0, 0, 0);
  18340. skyboxMaterial.disableLighting = true;
  18341. hdrSkybox.infiniteDistance = true;
  18342. hdrSkybox.material = skyboxMaterial;
  18343. }
  18344. return hdrSkybox;
  18345. };
  18346. // Tags
  18347. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  18348. if (tagsQuery === undefined) {
  18349. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  18350. return list;
  18351. }
  18352. var listByTags = [];
  18353. forEach = forEach || (function (item) { return; });
  18354. for (var i in list) {
  18355. var item = list[i];
  18356. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  18357. listByTags.push(item);
  18358. forEach(item);
  18359. }
  18360. }
  18361. return listByTags;
  18362. };
  18363. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  18364. return this._getByTags(this.meshes, tagsQuery, forEach);
  18365. };
  18366. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  18367. return this._getByTags(this.cameras, tagsQuery, forEach);
  18368. };
  18369. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  18370. return this._getByTags(this.lights, tagsQuery, forEach);
  18371. };
  18372. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  18373. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  18374. };
  18375. /**
  18376. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18377. * This allowed control for front to back rendering or reversly depending of the special needs.
  18378. *
  18379. * @param renderingGroupId The rendering group id corresponding to its index
  18380. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18381. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18382. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18383. */
  18384. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18385. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18386. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18387. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18388. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  18389. };
  18390. /**
  18391. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18392. *
  18393. * @param renderingGroupId The rendering group id corresponding to its index
  18394. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18395. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18396. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18397. */
  18398. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18399. if (depth === void 0) { depth = true; }
  18400. if (stencil === void 0) { stencil = true; }
  18401. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  18402. };
  18403. /**
  18404. * Will flag all materials as dirty to trigger new shader compilation
  18405. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  18406. */
  18407. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  18408. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  18409. var material = _a[_i];
  18410. if (predicate && !predicate(material)) {
  18411. continue;
  18412. }
  18413. material.markAsDirty(flag);
  18414. }
  18415. };
  18416. return Scene;
  18417. }());
  18418. // Statics
  18419. Scene._FOGMODE_NONE = 0;
  18420. Scene._FOGMODE_EXP = 1;
  18421. Scene._FOGMODE_EXP2 = 2;
  18422. Scene._FOGMODE_LINEAR = 3;
  18423. Scene.MinDeltaTime = 1.0;
  18424. Scene.MaxDeltaTime = 1000.0;
  18425. Scene.DragMovementThreshold = 10; // in pixels
  18426. Scene.LongPressDelay = 500; // in milliseconds
  18427. Scene.DoubleClickDelay = 300; // in milliseconds
  18428. Scene.ExclusiveDoubleClickMode = false; // If you need to check double click without raising a single click at first click, enable this flag
  18429. BABYLON.Scene = Scene;
  18430. })(BABYLON || (BABYLON = {}));
  18431. //# sourceMappingURL=babylon.scene.js.map
  18432. var BABYLON;
  18433. (function (BABYLON) {
  18434. var Buffer = (function () {
  18435. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  18436. if (engine instanceof BABYLON.Mesh) {
  18437. this._engine = engine.getScene().getEngine();
  18438. }
  18439. else {
  18440. this._engine = engine;
  18441. }
  18442. this._updatable = updatable;
  18443. this._data = data;
  18444. this._strideSize = stride;
  18445. if (!postponeInternalCreation) {
  18446. this.create();
  18447. }
  18448. this._instanced = instanced;
  18449. }
  18450. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  18451. // a lot of these parameters are ignored as they are overriden by the buffer
  18452. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  18453. };
  18454. // Properties
  18455. Buffer.prototype.isUpdatable = function () {
  18456. return this._updatable;
  18457. };
  18458. Buffer.prototype.getData = function () {
  18459. return this._data;
  18460. };
  18461. Buffer.prototype.getBuffer = function () {
  18462. return this._buffer;
  18463. };
  18464. Buffer.prototype.getStrideSize = function () {
  18465. return this._strideSize;
  18466. };
  18467. Buffer.prototype.getIsInstanced = function () {
  18468. return this._instanced;
  18469. };
  18470. // Methods
  18471. Buffer.prototype.create = function (data) {
  18472. if (!data && this._buffer) {
  18473. return; // nothing to do
  18474. }
  18475. data = data || this._data;
  18476. if (!this._buffer) {
  18477. if (this._updatable) {
  18478. this._buffer = this._engine.createDynamicVertexBuffer(data);
  18479. this._data = data;
  18480. }
  18481. else {
  18482. this._buffer = this._engine.createVertexBuffer(data);
  18483. }
  18484. }
  18485. else if (this._updatable) {
  18486. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  18487. this._data = data;
  18488. }
  18489. };
  18490. Buffer.prototype.update = function (data) {
  18491. this.create(data);
  18492. };
  18493. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  18494. if (!this._buffer) {
  18495. return;
  18496. }
  18497. if (this._updatable) {
  18498. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  18499. this._data = null;
  18500. }
  18501. };
  18502. Buffer.prototype.dispose = function () {
  18503. if (!this._buffer) {
  18504. return;
  18505. }
  18506. if (this._engine._releaseBuffer(this._buffer)) {
  18507. this._buffer = null;
  18508. }
  18509. };
  18510. return Buffer;
  18511. }());
  18512. BABYLON.Buffer = Buffer;
  18513. })(BABYLON || (BABYLON = {}));
  18514. //# sourceMappingURL=babylon.buffer.js.map
  18515. var BABYLON;
  18516. (function (BABYLON) {
  18517. var VertexBuffer = (function () {
  18518. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  18519. if (!stride) {
  18520. // Deduce stride from kind
  18521. switch (kind) {
  18522. case VertexBuffer.PositionKind:
  18523. stride = 3;
  18524. break;
  18525. case VertexBuffer.NormalKind:
  18526. stride = 3;
  18527. break;
  18528. case VertexBuffer.UVKind:
  18529. case VertexBuffer.UV2Kind:
  18530. case VertexBuffer.UV3Kind:
  18531. case VertexBuffer.UV4Kind:
  18532. case VertexBuffer.UV5Kind:
  18533. case VertexBuffer.UV6Kind:
  18534. stride = 2;
  18535. break;
  18536. case VertexBuffer.TangentKind:
  18537. case VertexBuffer.ColorKind:
  18538. stride = 4;
  18539. break;
  18540. case VertexBuffer.MatricesIndicesKind:
  18541. case VertexBuffer.MatricesIndicesExtraKind:
  18542. stride = 4;
  18543. break;
  18544. case VertexBuffer.MatricesWeightsKind:
  18545. case VertexBuffer.MatricesWeightsExtraKind:
  18546. stride = 4;
  18547. break;
  18548. }
  18549. }
  18550. if (data instanceof BABYLON.Buffer) {
  18551. if (!stride) {
  18552. stride = data.getStrideSize();
  18553. }
  18554. this._buffer = data;
  18555. this._ownsBuffer = false;
  18556. }
  18557. else {
  18558. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  18559. this._ownsBuffer = true;
  18560. }
  18561. this._stride = stride;
  18562. this._offset = offset ? offset : 0;
  18563. this._size = size ? size : stride;
  18564. this._kind = kind;
  18565. }
  18566. /**
  18567. * Returns the kind of the VertexBuffer (string).
  18568. */
  18569. VertexBuffer.prototype.getKind = function () {
  18570. return this._kind;
  18571. };
  18572. // Properties
  18573. /**
  18574. * Boolean : is the VertexBuffer updatable ?
  18575. */
  18576. VertexBuffer.prototype.isUpdatable = function () {
  18577. return this._buffer.isUpdatable();
  18578. };
  18579. /**
  18580. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  18581. */
  18582. VertexBuffer.prototype.getData = function () {
  18583. return this._buffer.getData();
  18584. };
  18585. /**
  18586. * Returns the WebGLBuffer associated to the VertexBuffer.
  18587. */
  18588. VertexBuffer.prototype.getBuffer = function () {
  18589. return this._buffer.getBuffer();
  18590. };
  18591. /**
  18592. * Returns the stride of the VertexBuffer (integer).
  18593. */
  18594. VertexBuffer.prototype.getStrideSize = function () {
  18595. return this._stride;
  18596. };
  18597. /**
  18598. * Returns the offset (integer).
  18599. */
  18600. VertexBuffer.prototype.getOffset = function () {
  18601. return this._offset;
  18602. };
  18603. /**
  18604. * Returns the VertexBuffer total size (integer).
  18605. */
  18606. VertexBuffer.prototype.getSize = function () {
  18607. return this._size;
  18608. };
  18609. /**
  18610. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  18611. */
  18612. VertexBuffer.prototype.getIsInstanced = function () {
  18613. return this._buffer.getIsInstanced();
  18614. };
  18615. // Methods
  18616. /**
  18617. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  18618. * Returns the created WebGLBuffer.
  18619. */
  18620. VertexBuffer.prototype.create = function (data) {
  18621. return this._buffer.create(data);
  18622. };
  18623. /**
  18624. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  18625. * Returns the updated WebGLBuffer.
  18626. */
  18627. VertexBuffer.prototype.update = function (data) {
  18628. return this._buffer.update(data);
  18629. };
  18630. /**
  18631. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  18632. * Returns the directly updated WebGLBuffer.
  18633. */
  18634. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  18635. return this._buffer.updateDirectly(data, offset);
  18636. };
  18637. /**
  18638. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  18639. */
  18640. VertexBuffer.prototype.dispose = function () {
  18641. if (this._ownsBuffer) {
  18642. this._buffer.dispose();
  18643. }
  18644. };
  18645. Object.defineProperty(VertexBuffer, "PositionKind", {
  18646. get: function () {
  18647. return VertexBuffer._PositionKind;
  18648. },
  18649. enumerable: true,
  18650. configurable: true
  18651. });
  18652. Object.defineProperty(VertexBuffer, "NormalKind", {
  18653. get: function () {
  18654. return VertexBuffer._NormalKind;
  18655. },
  18656. enumerable: true,
  18657. configurable: true
  18658. });
  18659. Object.defineProperty(VertexBuffer, "TangentKind", {
  18660. get: function () {
  18661. return VertexBuffer._TangentKind;
  18662. },
  18663. enumerable: true,
  18664. configurable: true
  18665. });
  18666. Object.defineProperty(VertexBuffer, "UVKind", {
  18667. get: function () {
  18668. return VertexBuffer._UVKind;
  18669. },
  18670. enumerable: true,
  18671. configurable: true
  18672. });
  18673. Object.defineProperty(VertexBuffer, "UV2Kind", {
  18674. get: function () {
  18675. return VertexBuffer._UV2Kind;
  18676. },
  18677. enumerable: true,
  18678. configurable: true
  18679. });
  18680. Object.defineProperty(VertexBuffer, "UV3Kind", {
  18681. get: function () {
  18682. return VertexBuffer._UV3Kind;
  18683. },
  18684. enumerable: true,
  18685. configurable: true
  18686. });
  18687. Object.defineProperty(VertexBuffer, "UV4Kind", {
  18688. get: function () {
  18689. return VertexBuffer._UV4Kind;
  18690. },
  18691. enumerable: true,
  18692. configurable: true
  18693. });
  18694. Object.defineProperty(VertexBuffer, "UV5Kind", {
  18695. get: function () {
  18696. return VertexBuffer._UV5Kind;
  18697. },
  18698. enumerable: true,
  18699. configurable: true
  18700. });
  18701. Object.defineProperty(VertexBuffer, "UV6Kind", {
  18702. get: function () {
  18703. return VertexBuffer._UV6Kind;
  18704. },
  18705. enumerable: true,
  18706. configurable: true
  18707. });
  18708. Object.defineProperty(VertexBuffer, "ColorKind", {
  18709. get: function () {
  18710. return VertexBuffer._ColorKind;
  18711. },
  18712. enumerable: true,
  18713. configurable: true
  18714. });
  18715. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  18716. get: function () {
  18717. return VertexBuffer._MatricesIndicesKind;
  18718. },
  18719. enumerable: true,
  18720. configurable: true
  18721. });
  18722. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  18723. get: function () {
  18724. return VertexBuffer._MatricesWeightsKind;
  18725. },
  18726. enumerable: true,
  18727. configurable: true
  18728. });
  18729. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  18730. get: function () {
  18731. return VertexBuffer._MatricesIndicesExtraKind;
  18732. },
  18733. enumerable: true,
  18734. configurable: true
  18735. });
  18736. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  18737. get: function () {
  18738. return VertexBuffer._MatricesWeightsExtraKind;
  18739. },
  18740. enumerable: true,
  18741. configurable: true
  18742. });
  18743. return VertexBuffer;
  18744. }());
  18745. // Enums
  18746. VertexBuffer._PositionKind = "position";
  18747. VertexBuffer._NormalKind = "normal";
  18748. VertexBuffer._TangentKind = "tangent";
  18749. VertexBuffer._UVKind = "uv";
  18750. VertexBuffer._UV2Kind = "uv2";
  18751. VertexBuffer._UV3Kind = "uv3";
  18752. VertexBuffer._UV4Kind = "uv4";
  18753. VertexBuffer._UV5Kind = "uv5";
  18754. VertexBuffer._UV6Kind = "uv6";
  18755. VertexBuffer._ColorKind = "color";
  18756. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  18757. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  18758. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  18759. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  18760. BABYLON.VertexBuffer = VertexBuffer;
  18761. })(BABYLON || (BABYLON = {}));
  18762. //# sourceMappingURL=babylon.vertexBuffer.js.map
  18763. var BABYLON;
  18764. (function (BABYLON) {
  18765. var BaseTexture = (function () {
  18766. function BaseTexture(scene) {
  18767. this._hasAlpha = false;
  18768. this.getAlphaFromRGB = false;
  18769. this.level = 1;
  18770. this.coordinatesIndex = 0;
  18771. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  18772. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18773. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18774. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  18775. this.isCube = false;
  18776. this.isRenderTarget = false;
  18777. this.animations = new Array();
  18778. /**
  18779. * An event triggered when the texture is disposed.
  18780. * @type {BABYLON.Observable}
  18781. */
  18782. this.onDisposeObservable = new BABYLON.Observable();
  18783. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18784. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  18785. this._scene.textures.push(this);
  18786. this._uid = null;
  18787. }
  18788. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  18789. get: function () {
  18790. return this._hasAlpha;
  18791. },
  18792. set: function (value) {
  18793. if (this._hasAlpha === value) {
  18794. return;
  18795. }
  18796. this._hasAlpha = value;
  18797. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18798. },
  18799. enumerable: true,
  18800. configurable: true
  18801. });
  18802. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  18803. get: function () {
  18804. return this._coordinatesMode;
  18805. },
  18806. set: function (value) {
  18807. if (this._coordinatesMode === value) {
  18808. return;
  18809. }
  18810. this._coordinatesMode = value;
  18811. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18812. },
  18813. enumerable: true,
  18814. configurable: true
  18815. });
  18816. Object.defineProperty(BaseTexture.prototype, "uid", {
  18817. get: function () {
  18818. if (!this._uid) {
  18819. this._uid = BABYLON.Tools.RandomId();
  18820. }
  18821. return this._uid;
  18822. },
  18823. enumerable: true,
  18824. configurable: true
  18825. });
  18826. BaseTexture.prototype.toString = function () {
  18827. return this.name;
  18828. };
  18829. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  18830. set: function (callback) {
  18831. if (this._onDisposeObserver) {
  18832. this.onDisposeObservable.remove(this._onDisposeObserver);
  18833. }
  18834. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18835. },
  18836. enumerable: true,
  18837. configurable: true
  18838. });
  18839. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  18840. get: function () {
  18841. return true;
  18842. },
  18843. enumerable: true,
  18844. configurable: true
  18845. });
  18846. BaseTexture.prototype.getScene = function () {
  18847. return this._scene;
  18848. };
  18849. BaseTexture.prototype.getTextureMatrix = function () {
  18850. return null;
  18851. };
  18852. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  18853. return null;
  18854. };
  18855. BaseTexture.prototype.getInternalTexture = function () {
  18856. return this._texture;
  18857. };
  18858. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  18859. return !this.isBlocking || this.isReady();
  18860. };
  18861. BaseTexture.prototype.isReady = function () {
  18862. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18863. this.delayLoad();
  18864. return false;
  18865. }
  18866. if (this._texture) {
  18867. return this._texture.isReady;
  18868. }
  18869. return false;
  18870. };
  18871. BaseTexture.prototype.getSize = function () {
  18872. if (this._texture._width) {
  18873. return new BABYLON.Size(this._texture._width, this._texture._height);
  18874. }
  18875. if (this._texture._size) {
  18876. return new BABYLON.Size(this._texture._size, this._texture._size);
  18877. }
  18878. return BABYLON.Size.Zero();
  18879. };
  18880. BaseTexture.prototype.getBaseSize = function () {
  18881. if (!this.isReady() || !this._texture)
  18882. return BABYLON.Size.Zero();
  18883. if (this._texture._size) {
  18884. return new BABYLON.Size(this._texture._size, this._texture._size);
  18885. }
  18886. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  18887. };
  18888. BaseTexture.prototype.scale = function (ratio) {
  18889. };
  18890. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  18891. get: function () {
  18892. return false;
  18893. },
  18894. enumerable: true,
  18895. configurable: true
  18896. });
  18897. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  18898. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  18899. for (var index = 0; index < texturesCache.length; index++) {
  18900. var texturesCacheEntry = texturesCache[index];
  18901. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  18902. texturesCache.splice(index, 1);
  18903. return;
  18904. }
  18905. }
  18906. };
  18907. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  18908. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  18909. for (var index = 0; index < texturesCache.length; index++) {
  18910. var texturesCacheEntry = texturesCache[index];
  18911. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  18912. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  18913. texturesCacheEntry.references++;
  18914. return texturesCacheEntry;
  18915. }
  18916. }
  18917. }
  18918. return null;
  18919. };
  18920. BaseTexture.prototype.delayLoad = function () {
  18921. };
  18922. BaseTexture.prototype.clone = function () {
  18923. return null;
  18924. };
  18925. BaseTexture.prototype.releaseInternalTexture = function () {
  18926. if (this._texture) {
  18927. this._scene.getEngine().releaseInternalTexture(this._texture);
  18928. delete this._texture;
  18929. }
  18930. };
  18931. BaseTexture.prototype.dispose = function () {
  18932. // Animations
  18933. this.getScene().stopAnimation(this);
  18934. // Remove from scene
  18935. this._scene._removePendingData(this);
  18936. var index = this._scene.textures.indexOf(this);
  18937. if (index >= 0) {
  18938. this._scene.textures.splice(index, 1);
  18939. }
  18940. if (this._texture === undefined) {
  18941. return;
  18942. }
  18943. // Release
  18944. this.releaseInternalTexture();
  18945. // Callback
  18946. this.onDisposeObservable.notifyObservers(this);
  18947. this.onDisposeObservable.clear();
  18948. };
  18949. BaseTexture.prototype.serialize = function () {
  18950. if (!this.name) {
  18951. return null;
  18952. }
  18953. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18954. // Animations
  18955. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18956. return serializationObject;
  18957. };
  18958. return BaseTexture;
  18959. }());
  18960. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  18961. __decorate([
  18962. BABYLON.serialize()
  18963. ], BaseTexture.prototype, "name", void 0);
  18964. __decorate([
  18965. BABYLON.serialize("hasAlpha")
  18966. ], BaseTexture.prototype, "_hasAlpha", void 0);
  18967. __decorate([
  18968. BABYLON.serialize()
  18969. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  18970. __decorate([
  18971. BABYLON.serialize()
  18972. ], BaseTexture.prototype, "level", void 0);
  18973. __decorate([
  18974. BABYLON.serialize()
  18975. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  18976. __decorate([
  18977. BABYLON.serialize("coordinatesMode")
  18978. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  18979. __decorate([
  18980. BABYLON.serialize()
  18981. ], BaseTexture.prototype, "wrapU", void 0);
  18982. __decorate([
  18983. BABYLON.serialize()
  18984. ], BaseTexture.prototype, "wrapV", void 0);
  18985. __decorate([
  18986. BABYLON.serialize()
  18987. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  18988. __decorate([
  18989. BABYLON.serialize()
  18990. ], BaseTexture.prototype, "isCube", void 0);
  18991. __decorate([
  18992. BABYLON.serialize()
  18993. ], BaseTexture.prototype, "isRenderTarget", void 0);
  18994. BABYLON.BaseTexture = BaseTexture;
  18995. })(BABYLON || (BABYLON = {}));
  18996. //# sourceMappingURL=babylon.baseTexture.js.map
  18997. var BABYLON;
  18998. (function (BABYLON) {
  18999. var Texture = (function (_super) {
  19000. __extends(Texture, _super);
  19001. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  19002. if (noMipmap === void 0) { noMipmap = false; }
  19003. if (invertY === void 0) { invertY = true; }
  19004. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19005. if (onLoad === void 0) { onLoad = null; }
  19006. if (onError === void 0) { onError = null; }
  19007. if (buffer === void 0) { buffer = null; }
  19008. if (deleteBuffer === void 0) { deleteBuffer = false; }
  19009. var _this = _super.call(this, scene) || this;
  19010. _this.uOffset = 0;
  19011. _this.vOffset = 0;
  19012. _this.uScale = 1.0;
  19013. _this.vScale = 1.0;
  19014. _this.uAng = 0;
  19015. _this.vAng = 0;
  19016. _this.wAng = 0;
  19017. _this._isBlocking = true;
  19018. _this.name = url;
  19019. _this.url = url;
  19020. _this._noMipmap = noMipmap;
  19021. _this._invertY = invertY;
  19022. _this._samplingMode = samplingMode;
  19023. _this._buffer = buffer;
  19024. _this._deleteBuffer = deleteBuffer;
  19025. _this._format = format;
  19026. scene = _this.getScene();
  19027. var load = function () {
  19028. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  19029. _this.onLoadObservable.notifyObservers(true);
  19030. }
  19031. if (onLoad) {
  19032. onLoad();
  19033. }
  19034. if (!_this.isBlocking) {
  19035. scene.resetCachedMaterial();
  19036. }
  19037. };
  19038. if (!url) {
  19039. _this._delayedOnLoad = load;
  19040. _this._delayedOnError = onError;
  19041. return _this;
  19042. }
  19043. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  19044. if (!_this._texture) {
  19045. if (!scene.useDelayedTextureLoading) {
  19046. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  19047. if (deleteBuffer) {
  19048. delete _this._buffer;
  19049. }
  19050. }
  19051. else {
  19052. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19053. _this._delayedOnLoad = load;
  19054. _this._delayedOnError = onError;
  19055. }
  19056. }
  19057. else {
  19058. if (_this._texture.isReady) {
  19059. BABYLON.Tools.SetImmediate(function () { return load(); });
  19060. }
  19061. else {
  19062. _this._texture.onLoadedCallbacks.push(load);
  19063. }
  19064. }
  19065. return _this;
  19066. }
  19067. Object.defineProperty(Texture.prototype, "noMipmap", {
  19068. get: function () {
  19069. return this._noMipmap;
  19070. },
  19071. enumerable: true,
  19072. configurable: true
  19073. });
  19074. Object.defineProperty(Texture.prototype, "isBlocking", {
  19075. get: function () {
  19076. return this._isBlocking;
  19077. },
  19078. set: function (value) {
  19079. this._isBlocking = value;
  19080. },
  19081. enumerable: true,
  19082. configurable: true
  19083. });
  19084. Texture.prototype.updateURL = function (url) {
  19085. this.url = url;
  19086. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19087. this.delayLoad();
  19088. };
  19089. Texture.prototype.delayLoad = function () {
  19090. var _this = this;
  19091. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19092. return;
  19093. }
  19094. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19095. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  19096. if (!this._texture) {
  19097. 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);
  19098. if (this._deleteBuffer) {
  19099. delete this._buffer;
  19100. }
  19101. }
  19102. else {
  19103. if (this._texture.isReady) {
  19104. BABYLON.Tools.SetImmediate(function () { return _this._delayedOnLoad(); });
  19105. }
  19106. else {
  19107. this._texture.onLoadedCallbacks.push(this._delayedOnLoad);
  19108. }
  19109. }
  19110. };
  19111. Texture.prototype.updateSamplingMode = function (samplingMode) {
  19112. if (!this._texture) {
  19113. return;
  19114. }
  19115. this._samplingMode = samplingMode;
  19116. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  19117. };
  19118. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  19119. x *= this.uScale;
  19120. y *= this.vScale;
  19121. x -= 0.5 * this.uScale;
  19122. y -= 0.5 * this.vScale;
  19123. z -= 0.5;
  19124. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  19125. t.x += 0.5 * this.uScale + this.uOffset;
  19126. t.y += 0.5 * this.vScale + this.vOffset;
  19127. t.z += 0.5;
  19128. };
  19129. Texture.prototype.getTextureMatrix = function () {
  19130. if (this.uOffset === this._cachedUOffset &&
  19131. this.vOffset === this._cachedVOffset &&
  19132. this.uScale === this._cachedUScale &&
  19133. this.vScale === this._cachedVScale &&
  19134. this.uAng === this._cachedUAng &&
  19135. this.vAng === this._cachedVAng &&
  19136. this.wAng === this._cachedWAng) {
  19137. return this._cachedTextureMatrix;
  19138. }
  19139. this._cachedUOffset = this.uOffset;
  19140. this._cachedVOffset = this.vOffset;
  19141. this._cachedUScale = this.uScale;
  19142. this._cachedVScale = this.vScale;
  19143. this._cachedUAng = this.uAng;
  19144. this._cachedVAng = this.vAng;
  19145. this._cachedWAng = this.wAng;
  19146. if (!this._cachedTextureMatrix) {
  19147. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19148. this._rowGenerationMatrix = new BABYLON.Matrix();
  19149. this._t0 = BABYLON.Vector3.Zero();
  19150. this._t1 = BABYLON.Vector3.Zero();
  19151. this._t2 = BABYLON.Vector3.Zero();
  19152. }
  19153. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  19154. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  19155. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  19156. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  19157. this._t1.subtractInPlace(this._t0);
  19158. this._t2.subtractInPlace(this._t0);
  19159. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19160. this._cachedTextureMatrix.m[0] = this._t1.x;
  19161. this._cachedTextureMatrix.m[1] = this._t1.y;
  19162. this._cachedTextureMatrix.m[2] = this._t1.z;
  19163. this._cachedTextureMatrix.m[4] = this._t2.x;
  19164. this._cachedTextureMatrix.m[5] = this._t2.y;
  19165. this._cachedTextureMatrix.m[6] = this._t2.z;
  19166. this._cachedTextureMatrix.m[8] = this._t0.x;
  19167. this._cachedTextureMatrix.m[9] = this._t0.y;
  19168. this._cachedTextureMatrix.m[10] = this._t0.z;
  19169. return this._cachedTextureMatrix;
  19170. };
  19171. Texture.prototype.getReflectionTextureMatrix = function () {
  19172. if (this.uOffset === this._cachedUOffset &&
  19173. this.vOffset === this._cachedVOffset &&
  19174. this.uScale === this._cachedUScale &&
  19175. this.vScale === this._cachedVScale &&
  19176. this.coordinatesMode === this._cachedCoordinatesMode) {
  19177. return this._cachedTextureMatrix;
  19178. }
  19179. if (!this._cachedTextureMatrix) {
  19180. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19181. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  19182. }
  19183. this._cachedCoordinatesMode = this.coordinatesMode;
  19184. switch (this.coordinatesMode) {
  19185. case Texture.PLANAR_MODE:
  19186. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19187. this._cachedTextureMatrix[0] = this.uScale;
  19188. this._cachedTextureMatrix[5] = this.vScale;
  19189. this._cachedTextureMatrix[12] = this.uOffset;
  19190. this._cachedTextureMatrix[13] = this.vOffset;
  19191. break;
  19192. case Texture.PROJECTION_MODE:
  19193. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  19194. this._projectionModeMatrix.m[0] = 0.5;
  19195. this._projectionModeMatrix.m[5] = -0.5;
  19196. this._projectionModeMatrix.m[10] = 0.0;
  19197. this._projectionModeMatrix.m[12] = 0.5;
  19198. this._projectionModeMatrix.m[13] = 0.5;
  19199. this._projectionModeMatrix.m[14] = 1.0;
  19200. this._projectionModeMatrix.m[15] = 1.0;
  19201. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  19202. break;
  19203. default:
  19204. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19205. break;
  19206. }
  19207. return this._cachedTextureMatrix;
  19208. };
  19209. Texture.prototype.clone = function () {
  19210. var _this = this;
  19211. return BABYLON.SerializationHelper.Clone(function () {
  19212. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  19213. }, this);
  19214. };
  19215. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  19216. get: function () {
  19217. if (!this._onLoadObservarble) {
  19218. this._onLoadObservarble = new BABYLON.Observable();
  19219. }
  19220. return this._onLoadObservarble;
  19221. },
  19222. enumerable: true,
  19223. configurable: true
  19224. });
  19225. // Statics
  19226. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  19227. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19228. if (onLoad === void 0) { onLoad = null; }
  19229. if (onError === void 0) { onError = null; }
  19230. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  19231. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  19232. };
  19233. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  19234. if (parsedTexture.customType) {
  19235. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  19236. // Update Sampling Mode
  19237. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  19238. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  19239. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  19240. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  19241. }
  19242. }
  19243. return parsedCustomTexture;
  19244. }
  19245. if (parsedTexture.isCube) {
  19246. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  19247. }
  19248. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19249. return null;
  19250. }
  19251. var texture = BABYLON.SerializationHelper.Parse(function () {
  19252. if (parsedTexture.mirrorPlane) {
  19253. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19254. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  19255. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19256. return mirrorTexture;
  19257. }
  19258. else if (parsedTexture.isRenderTarget) {
  19259. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19260. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  19261. return renderTargetTexture;
  19262. }
  19263. else {
  19264. var texture;
  19265. if (parsedTexture.base64String) {
  19266. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19267. }
  19268. else {
  19269. texture = new Texture(rootUrl + parsedTexture.name, scene);
  19270. }
  19271. return texture;
  19272. }
  19273. }, parsedTexture, scene);
  19274. // Update Sampling Mode
  19275. if (parsedTexture.samplingMode) {
  19276. var sampling = parsedTexture.samplingMode;
  19277. if (texture._samplingMode !== sampling) {
  19278. texture.updateSamplingMode(sampling);
  19279. }
  19280. }
  19281. // Animations
  19282. if (parsedTexture.animations) {
  19283. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19284. var parsedAnimation = parsedTexture.animations[animationIndex];
  19285. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19286. }
  19287. }
  19288. return texture;
  19289. };
  19290. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  19291. if (deleteBuffer === void 0) { deleteBuffer = false; }
  19292. if (noMipmap === void 0) { noMipmap = false; }
  19293. if (invertY === void 0) { invertY = true; }
  19294. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19295. if (onLoad === void 0) { onLoad = null; }
  19296. if (onError === void 0) { onError = null; }
  19297. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  19298. if (name.substr(0, 5) !== "data:") {
  19299. name = "data:" + name;
  19300. }
  19301. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  19302. };
  19303. return Texture;
  19304. }(BABYLON.BaseTexture));
  19305. // Constants
  19306. Texture.NEAREST_SAMPLINGMODE = 1;
  19307. Texture.BILINEAR_SAMPLINGMODE = 2;
  19308. Texture.TRILINEAR_SAMPLINGMODE = 3;
  19309. Texture.EXPLICIT_MODE = 0;
  19310. Texture.SPHERICAL_MODE = 1;
  19311. Texture.PLANAR_MODE = 2;
  19312. Texture.CUBIC_MODE = 3;
  19313. Texture.PROJECTION_MODE = 4;
  19314. Texture.SKYBOX_MODE = 5;
  19315. Texture.INVCUBIC_MODE = 6;
  19316. Texture.EQUIRECTANGULAR_MODE = 7;
  19317. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  19318. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  19319. Texture.CLAMP_ADDRESSMODE = 0;
  19320. Texture.WRAP_ADDRESSMODE = 1;
  19321. Texture.MIRROR_ADDRESSMODE = 2;
  19322. __decorate([
  19323. BABYLON.serialize()
  19324. ], Texture.prototype, "url", void 0);
  19325. __decorate([
  19326. BABYLON.serialize()
  19327. ], Texture.prototype, "uOffset", void 0);
  19328. __decorate([
  19329. BABYLON.serialize()
  19330. ], Texture.prototype, "vOffset", void 0);
  19331. __decorate([
  19332. BABYLON.serialize()
  19333. ], Texture.prototype, "uScale", void 0);
  19334. __decorate([
  19335. BABYLON.serialize()
  19336. ], Texture.prototype, "vScale", void 0);
  19337. __decorate([
  19338. BABYLON.serialize()
  19339. ], Texture.prototype, "uAng", void 0);
  19340. __decorate([
  19341. BABYLON.serialize()
  19342. ], Texture.prototype, "vAng", void 0);
  19343. __decorate([
  19344. BABYLON.serialize()
  19345. ], Texture.prototype, "wAng", void 0);
  19346. __decorate([
  19347. BABYLON.serialize()
  19348. ], Texture.prototype, "isBlocking", null);
  19349. BABYLON.Texture = Texture;
  19350. })(BABYLON || (BABYLON = {}));
  19351. //# sourceMappingURL=babylon.texture.js.map
  19352. var BABYLON;
  19353. (function (BABYLON) {
  19354. var _InstancesBatch = (function () {
  19355. function _InstancesBatch() {
  19356. this.mustReturn = false;
  19357. this.visibleInstances = new Array();
  19358. this.renderSelf = new Array();
  19359. }
  19360. return _InstancesBatch;
  19361. }());
  19362. BABYLON._InstancesBatch = _InstancesBatch;
  19363. var Mesh = (function (_super) {
  19364. __extends(Mesh, _super);
  19365. /**
  19366. * @constructor
  19367. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  19368. * @param {Scene} scene The scene to add this mesh to.
  19369. * @param {Node} parent The parent of this mesh, if it has one
  19370. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  19371. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  19372. * When false, achieved by calling a clone(), also passing False.
  19373. * This will make creation of children, recursive.
  19374. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  19375. */
  19376. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  19377. if (parent === void 0) { parent = null; }
  19378. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19379. var _this = _super.call(this, name, scene) || this;
  19380. // Events
  19381. /**
  19382. * An event triggered before rendering the mesh
  19383. * @type {BABYLON.Observable}
  19384. */
  19385. _this.onBeforeRenderObservable = new BABYLON.Observable();
  19386. /**
  19387. * An event triggered after rendering the mesh
  19388. * @type {BABYLON.Observable}
  19389. */
  19390. _this.onAfterRenderObservable = new BABYLON.Observable();
  19391. /**
  19392. * An event triggered before drawing the mesh
  19393. * @type {BABYLON.Observable}
  19394. */
  19395. _this.onBeforeDrawObservable = new BABYLON.Observable();
  19396. // Members
  19397. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19398. _this.instances = new Array();
  19399. _this._LODLevels = new Array();
  19400. _this._visibleInstances = {};
  19401. _this._renderIdForInstances = new Array();
  19402. _this._batchCache = new _InstancesBatch();
  19403. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  19404. _this._sideOrientation = Mesh._DEFAULTSIDE;
  19405. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  19406. // Will be used to save a source mesh reference, If any
  19407. _this._source = null;
  19408. if (source) {
  19409. // Source mesh
  19410. _this._source = source;
  19411. // Geometry
  19412. if (source._geometry) {
  19413. source._geometry.applyToMesh(_this);
  19414. }
  19415. // Deep copy
  19416. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  19417. // Parent
  19418. _this.parent = source.parent;
  19419. // Pivot
  19420. _this.setPivotMatrix(source.getPivotMatrix());
  19421. _this.id = name + "." + source.id;
  19422. // Material
  19423. _this.material = source.material;
  19424. var index;
  19425. if (!doNotCloneChildren) {
  19426. // Children
  19427. for (index = 0; index < scene.meshes.length; index++) {
  19428. var mesh = scene.meshes[index];
  19429. if (mesh.parent === source) {
  19430. // doNotCloneChildren is always going to be False
  19431. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  19432. }
  19433. }
  19434. }
  19435. // Physics clone
  19436. var physicsEngine = _this.getScene().getPhysicsEngine();
  19437. if (clonePhysicsImpostor && physicsEngine) {
  19438. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  19439. if (impostor) {
  19440. _this.physicsImpostor = impostor.clone(_this);
  19441. }
  19442. }
  19443. // Particles
  19444. for (index = 0; index < scene.particleSystems.length; index++) {
  19445. var system = scene.particleSystems[index];
  19446. if (system.emitter === source) {
  19447. system.clone(system.name, _this);
  19448. }
  19449. }
  19450. _this.computeWorldMatrix(true);
  19451. }
  19452. // Parent
  19453. if (parent !== null) {
  19454. _this.parent = parent;
  19455. }
  19456. return _this;
  19457. }
  19458. Object.defineProperty(Mesh, "FRONTSIDE", {
  19459. /**
  19460. * Mesh side orientation : usually the external or front surface
  19461. */
  19462. get: function () {
  19463. return Mesh._FRONTSIDE;
  19464. },
  19465. enumerable: true,
  19466. configurable: true
  19467. });
  19468. Object.defineProperty(Mesh, "BACKSIDE", {
  19469. /**
  19470. * Mesh side orientation : usually the internal or back surface
  19471. */
  19472. get: function () {
  19473. return Mesh._BACKSIDE;
  19474. },
  19475. enumerable: true,
  19476. configurable: true
  19477. });
  19478. Object.defineProperty(Mesh, "DOUBLESIDE", {
  19479. /**
  19480. * Mesh side orientation : both internal and external or front and back surfaces
  19481. */
  19482. get: function () {
  19483. return Mesh._DOUBLESIDE;
  19484. },
  19485. enumerable: true,
  19486. configurable: true
  19487. });
  19488. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  19489. /**
  19490. * Mesh side orientation : by default, `FRONTSIDE`
  19491. */
  19492. get: function () {
  19493. return Mesh._DEFAULTSIDE;
  19494. },
  19495. enumerable: true,
  19496. configurable: true
  19497. });
  19498. Object.defineProperty(Mesh, "NO_CAP", {
  19499. /**
  19500. * Mesh cap setting : no cap
  19501. */
  19502. get: function () {
  19503. return Mesh._NO_CAP;
  19504. },
  19505. enumerable: true,
  19506. configurable: true
  19507. });
  19508. Object.defineProperty(Mesh, "CAP_START", {
  19509. /**
  19510. * Mesh cap setting : one cap at the beginning of the mesh
  19511. */
  19512. get: function () {
  19513. return Mesh._CAP_START;
  19514. },
  19515. enumerable: true,
  19516. configurable: true
  19517. });
  19518. Object.defineProperty(Mesh, "CAP_END", {
  19519. /**
  19520. * Mesh cap setting : one cap at the end of the mesh
  19521. */
  19522. get: function () {
  19523. return Mesh._CAP_END;
  19524. },
  19525. enumerable: true,
  19526. configurable: true
  19527. });
  19528. Object.defineProperty(Mesh, "CAP_ALL", {
  19529. /**
  19530. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  19531. */
  19532. get: function () {
  19533. return Mesh._CAP_ALL;
  19534. },
  19535. enumerable: true,
  19536. configurable: true
  19537. });
  19538. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  19539. set: function (callback) {
  19540. if (this._onBeforeDrawObserver) {
  19541. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  19542. }
  19543. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  19544. },
  19545. enumerable: true,
  19546. configurable: true
  19547. });
  19548. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  19549. get: function () {
  19550. return this._morphTargetManager;
  19551. },
  19552. set: function (value) {
  19553. if (this._morphTargetManager === value) {
  19554. return;
  19555. }
  19556. this._morphTargetManager = value;
  19557. this._syncGeometryWithMorphTargetManager();
  19558. },
  19559. enumerable: true,
  19560. configurable: true
  19561. });
  19562. Object.defineProperty(Mesh.prototype, "source", {
  19563. get: function () {
  19564. return this._source;
  19565. },
  19566. enumerable: true,
  19567. configurable: true
  19568. });
  19569. // Methods
  19570. /**
  19571. * Returns the string "Mesh".
  19572. */
  19573. Mesh.prototype.getClassName = function () {
  19574. return "Mesh";
  19575. };
  19576. /**
  19577. * Returns a string.
  19578. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19579. */
  19580. Mesh.prototype.toString = function (fullDetails) {
  19581. var ret = _super.prototype.toString.call(this, fullDetails);
  19582. ret += ", n vertices: " + this.getTotalVertices();
  19583. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  19584. if (this.animations) {
  19585. for (var i = 0; i < this.animations.length; i++) {
  19586. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19587. }
  19588. }
  19589. if (fullDetails) {
  19590. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  19591. }
  19592. return ret;
  19593. };
  19594. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  19595. /**
  19596. * True if the mesh has some Levels Of Details (LOD).
  19597. * Returns a boolean.
  19598. */
  19599. get: function () {
  19600. return this._LODLevels.length > 0;
  19601. },
  19602. enumerable: true,
  19603. configurable: true
  19604. });
  19605. Mesh.prototype._sortLODLevels = function () {
  19606. this._LODLevels.sort(function (a, b) {
  19607. if (a.distance < b.distance) {
  19608. return 1;
  19609. }
  19610. if (a.distance > b.distance) {
  19611. return -1;
  19612. }
  19613. return 0;
  19614. });
  19615. };
  19616. /**
  19617. * Add a mesh as LOD level triggered at the given distance.
  19618. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19619. * @param {number} distance The distance from the center of the object to show this level
  19620. * @param {Mesh} mesh The mesh to be added as LOD level
  19621. * @return {Mesh} This mesh (for chaining)
  19622. */
  19623. Mesh.prototype.addLODLevel = function (distance, mesh) {
  19624. if (mesh && mesh._masterMesh) {
  19625. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  19626. return this;
  19627. }
  19628. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  19629. this._LODLevels.push(level);
  19630. if (mesh) {
  19631. mesh._masterMesh = this;
  19632. }
  19633. this._sortLODLevels();
  19634. return this;
  19635. };
  19636. /**
  19637. * Returns the LOD level mesh at the passed distance or null if not found.
  19638. * It is related to the method `addLODLevel(distance, mesh)`.
  19639. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19640. * Returns an object Mesh or `null`.
  19641. */
  19642. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  19643. for (var index = 0; index < this._LODLevels.length; index++) {
  19644. var level = this._LODLevels[index];
  19645. if (level.distance === distance) {
  19646. return level.mesh;
  19647. }
  19648. }
  19649. return null;
  19650. };
  19651. /**
  19652. * Remove a mesh from the LOD array
  19653. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19654. * @param {Mesh} mesh The mesh to be removed.
  19655. * @return {Mesh} This mesh (for chaining)
  19656. */
  19657. Mesh.prototype.removeLODLevel = function (mesh) {
  19658. for (var index = 0; index < this._LODLevels.length; index++) {
  19659. if (this._LODLevels[index].mesh === mesh) {
  19660. this._LODLevels.splice(index, 1);
  19661. if (mesh) {
  19662. mesh._masterMesh = null;
  19663. }
  19664. }
  19665. }
  19666. this._sortLODLevels();
  19667. return this;
  19668. };
  19669. /**
  19670. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  19671. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19672. */
  19673. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  19674. if (!this._LODLevels || this._LODLevels.length === 0) {
  19675. return this;
  19676. }
  19677. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  19678. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  19679. if (this.onLODLevelSelection) {
  19680. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  19681. }
  19682. return this;
  19683. }
  19684. for (var index = 0; index < this._LODLevels.length; index++) {
  19685. var level = this._LODLevels[index];
  19686. if (level.distance < distanceToCamera) {
  19687. if (level.mesh) {
  19688. level.mesh._preActivate();
  19689. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19690. }
  19691. if (this.onLODLevelSelection) {
  19692. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  19693. }
  19694. return level.mesh;
  19695. }
  19696. }
  19697. if (this.onLODLevelSelection) {
  19698. this.onLODLevelSelection(distanceToCamera, this, this);
  19699. }
  19700. return this;
  19701. };
  19702. Object.defineProperty(Mesh.prototype, "geometry", {
  19703. /**
  19704. * Returns the mesh internal Geometry object.
  19705. */
  19706. get: function () {
  19707. return this._geometry;
  19708. },
  19709. enumerable: true,
  19710. configurable: true
  19711. });
  19712. /**
  19713. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  19714. */
  19715. Mesh.prototype.getTotalVertices = function () {
  19716. if (!this._geometry) {
  19717. return 0;
  19718. }
  19719. return this._geometry.getTotalVertices();
  19720. };
  19721. /**
  19722. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  19723. * 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.
  19724. * You can force the copy with forceCopy === true
  19725. * Returns null if the mesh has no geometry or no vertex buffer.
  19726. * Possible `kind` values :
  19727. * - BABYLON.VertexBuffer.PositionKind
  19728. * - BABYLON.VertexBuffer.UVKind
  19729. * - BABYLON.VertexBuffer.UV2Kind
  19730. * - BABYLON.VertexBuffer.UV3Kind
  19731. * - BABYLON.VertexBuffer.UV4Kind
  19732. * - BABYLON.VertexBuffer.UV5Kind
  19733. * - BABYLON.VertexBuffer.UV6Kind
  19734. * - BABYLON.VertexBuffer.ColorKind
  19735. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19736. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19737. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19738. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19739. */
  19740. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  19741. if (!this._geometry) {
  19742. return null;
  19743. }
  19744. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  19745. };
  19746. /**
  19747. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  19748. * Returns `undefined` if the mesh has no geometry.
  19749. * Possible `kind` values :
  19750. * - BABYLON.VertexBuffer.PositionKind
  19751. * - BABYLON.VertexBuffer.UVKind
  19752. * - BABYLON.VertexBuffer.UV2Kind
  19753. * - BABYLON.VertexBuffer.UV3Kind
  19754. * - BABYLON.VertexBuffer.UV4Kind
  19755. * - BABYLON.VertexBuffer.UV5Kind
  19756. * - BABYLON.VertexBuffer.UV6Kind
  19757. * - BABYLON.VertexBuffer.ColorKind
  19758. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19759. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19760. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19761. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19762. */
  19763. Mesh.prototype.getVertexBuffer = function (kind) {
  19764. if (!this._geometry) {
  19765. return undefined;
  19766. }
  19767. return this._geometry.getVertexBuffer(kind);
  19768. };
  19769. /**
  19770. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  19771. * Possible `kind` values :
  19772. * - BABYLON.VertexBuffer.PositionKind
  19773. * - BABYLON.VertexBuffer.UVKind
  19774. * - BABYLON.VertexBuffer.UV2Kind
  19775. * - BABYLON.VertexBuffer.UV3Kind
  19776. * - BABYLON.VertexBuffer.UV4Kind
  19777. * - BABYLON.VertexBuffer.UV5Kind
  19778. * - BABYLON.VertexBuffer.UV6Kind
  19779. * - BABYLON.VertexBuffer.ColorKind
  19780. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19781. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19782. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19783. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19784. */
  19785. Mesh.prototype.isVerticesDataPresent = function (kind) {
  19786. if (!this._geometry) {
  19787. if (this._delayInfo) {
  19788. return this._delayInfo.indexOf(kind) !== -1;
  19789. }
  19790. return false;
  19791. }
  19792. return this._geometry.isVerticesDataPresent(kind);
  19793. };
  19794. /**
  19795. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  19796. * Possible `kind` values :
  19797. * - BABYLON.VertexBuffer.PositionKind
  19798. * - BABYLON.VertexBuffer.UVKind
  19799. * - BABYLON.VertexBuffer.UV2Kind
  19800. * - BABYLON.VertexBuffer.UV3Kind
  19801. * - BABYLON.VertexBuffer.UV4Kind
  19802. * - BABYLON.VertexBuffer.UV5Kind
  19803. * - BABYLON.VertexBuffer.UV6Kind
  19804. * - BABYLON.VertexBuffer.ColorKind
  19805. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19806. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19807. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19808. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19809. */
  19810. Mesh.prototype.getVerticesDataKinds = function () {
  19811. if (!this._geometry) {
  19812. var result = [];
  19813. if (this._delayInfo) {
  19814. this._delayInfo.forEach(function (kind, index, array) {
  19815. result.push(kind);
  19816. });
  19817. }
  19818. return result;
  19819. }
  19820. return this._geometry.getVerticesDataKinds();
  19821. };
  19822. /**
  19823. * Returns a positive integer : the total number of indices in this mesh geometry.
  19824. * Returns zero if the mesh has no geometry.
  19825. */
  19826. Mesh.prototype.getTotalIndices = function () {
  19827. if (!this._geometry) {
  19828. return 0;
  19829. }
  19830. return this._geometry.getTotalIndices();
  19831. };
  19832. /**
  19833. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  19834. * 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.
  19835. * Returns an empty array if the mesh has no geometry.
  19836. */
  19837. Mesh.prototype.getIndices = function (copyWhenShared) {
  19838. if (!this._geometry) {
  19839. return [];
  19840. }
  19841. return this._geometry.getIndices(copyWhenShared);
  19842. };
  19843. Object.defineProperty(Mesh.prototype, "isBlocked", {
  19844. get: function () {
  19845. return this._masterMesh !== null && this._masterMesh !== undefined;
  19846. },
  19847. enumerable: true,
  19848. configurable: true
  19849. });
  19850. /**
  19851. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  19852. */
  19853. Mesh.prototype.isReady = function () {
  19854. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19855. return false;
  19856. }
  19857. return _super.prototype.isReady.call(this);
  19858. };
  19859. /**
  19860. * Boolean : true if the mesh has been disposed.
  19861. */
  19862. Mesh.prototype.isDisposed = function () {
  19863. return this._isDisposed;
  19864. };
  19865. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  19866. get: function () {
  19867. return this._sideOrientation;
  19868. },
  19869. /**
  19870. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  19871. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  19872. */
  19873. set: function (sideO) {
  19874. this._sideOrientation = sideO;
  19875. },
  19876. enumerable: true,
  19877. configurable: true
  19878. });
  19879. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  19880. /**
  19881. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  19882. * This property is pertinent only for updatable parametric shapes.
  19883. */
  19884. get: function () {
  19885. return this._areNormalsFrozen;
  19886. },
  19887. enumerable: true,
  19888. configurable: true
  19889. });
  19890. /**
  19891. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19892. * It has no effect at all on other shapes.
  19893. * It prevents the mesh normals from being recomputed on next `positions` array update.
  19894. * Returns the Mesh.
  19895. */
  19896. Mesh.prototype.freezeNormals = function () {
  19897. this._areNormalsFrozen = true;
  19898. return this;
  19899. };
  19900. /**
  19901. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19902. * It has no effect at all on other shapes.
  19903. * It reactivates the mesh normals computation if it was previously frozen.
  19904. * Returns the Mesh.
  19905. */
  19906. Mesh.prototype.unfreezeNormals = function () {
  19907. this._areNormalsFrozen = false;
  19908. return this;
  19909. };
  19910. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  19911. /**
  19912. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  19913. */
  19914. set: function (count) {
  19915. this._overridenInstanceCount = count;
  19916. },
  19917. enumerable: true,
  19918. configurable: true
  19919. });
  19920. // Methods
  19921. Mesh.prototype._preActivate = function () {
  19922. var sceneRenderId = this.getScene().getRenderId();
  19923. if (this._preActivateId === sceneRenderId) {
  19924. return this;
  19925. }
  19926. this._preActivateId = sceneRenderId;
  19927. this._visibleInstances = null;
  19928. return this;
  19929. };
  19930. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  19931. if (this._visibleInstances) {
  19932. this._visibleInstances.intermediateDefaultRenderId = renderId;
  19933. }
  19934. return this;
  19935. };
  19936. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  19937. if (!this._visibleInstances) {
  19938. this._visibleInstances = {};
  19939. this._visibleInstances.defaultRenderId = renderId;
  19940. this._visibleInstances.selfDefaultRenderId = this._renderId;
  19941. }
  19942. if (!this._visibleInstances[renderId]) {
  19943. this._visibleInstances[renderId] = new Array();
  19944. }
  19945. this._visibleInstances[renderId].push(instance);
  19946. return this;
  19947. };
  19948. /**
  19949. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  19950. * This means the mesh underlying bounding box and sphere are recomputed.
  19951. * Returns the Mesh.
  19952. */
  19953. Mesh.prototype.refreshBoundingInfo = function () {
  19954. if (this._boundingInfo.isLocked) {
  19955. return;
  19956. }
  19957. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19958. if (data) {
  19959. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  19960. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19961. }
  19962. if (this.subMeshes) {
  19963. for (var index = 0; index < this.subMeshes.length; index++) {
  19964. this.subMeshes[index].refreshBoundingInfo();
  19965. }
  19966. }
  19967. this._updateBoundingInfo();
  19968. return this;
  19969. };
  19970. Mesh.prototype._createGlobalSubMesh = function () {
  19971. var totalVertices = this.getTotalVertices();
  19972. if (!totalVertices || !this.getIndices()) {
  19973. return null;
  19974. }
  19975. this.releaseSubMeshes();
  19976. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  19977. };
  19978. Mesh.prototype.subdivide = function (count) {
  19979. if (count < 1) {
  19980. return;
  19981. }
  19982. var totalIndices = this.getTotalIndices();
  19983. var subdivisionSize = (totalIndices / count) | 0;
  19984. var offset = 0;
  19985. // Ensure that subdivisionSize is a multiple of 3
  19986. while (subdivisionSize % 3 !== 0) {
  19987. subdivisionSize++;
  19988. }
  19989. this.releaseSubMeshes();
  19990. for (var index = 0; index < count; index++) {
  19991. if (offset >= totalIndices) {
  19992. break;
  19993. }
  19994. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  19995. offset += subdivisionSize;
  19996. }
  19997. this.synchronizeInstances();
  19998. };
  19999. /**
  20000. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20001. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20002. * The `data` are either a numeric array either a Float32Array.
  20003. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  20004. * 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).
  20005. * Note that a new underlying VertexBuffer object is created each call.
  20006. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20007. *
  20008. * Possible `kind` values :
  20009. * - BABYLON.VertexBuffer.PositionKind
  20010. * - BABYLON.VertexBuffer.UVKind
  20011. * - BABYLON.VertexBuffer.UV2Kind
  20012. * - BABYLON.VertexBuffer.UV3Kind
  20013. * - BABYLON.VertexBuffer.UV4Kind
  20014. * - BABYLON.VertexBuffer.UV5Kind
  20015. * - BABYLON.VertexBuffer.UV6Kind
  20016. * - BABYLON.VertexBuffer.ColorKind
  20017. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20018. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20019. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20020. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20021. *
  20022. * Returns the Mesh.
  20023. */
  20024. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20025. if (!this._geometry) {
  20026. var vertexData = new BABYLON.VertexData();
  20027. vertexData.set(data, kind);
  20028. var scene = this.getScene();
  20029. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  20030. }
  20031. else {
  20032. this._geometry.setVerticesData(kind, data, updatable, stride);
  20033. }
  20034. return this;
  20035. };
  20036. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  20037. if (updatable === void 0) { updatable = true; }
  20038. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  20039. return;
  20040. }
  20041. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  20042. };
  20043. /**
  20044. * Sets the mesh VertexBuffer.
  20045. * Returns the Mesh.
  20046. */
  20047. Mesh.prototype.setVerticesBuffer = function (buffer) {
  20048. if (!this._geometry) {
  20049. var scene = this.getScene();
  20050. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  20051. }
  20052. this._geometry.setVerticesBuffer(buffer);
  20053. return this;
  20054. };
  20055. /**
  20056. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20057. * If the mesh has no geometry, it is simply returned as it is.
  20058. * The `data` are either a numeric array either a Float32Array.
  20059. * No new underlying VertexBuffer object is created.
  20060. * 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.
  20061. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  20062. *
  20063. * Possible `kind` values :
  20064. * - BABYLON.VertexBuffer.PositionKind
  20065. * - BABYLON.VertexBuffer.UVKind
  20066. * - BABYLON.VertexBuffer.UV2Kind
  20067. * - BABYLON.VertexBuffer.UV3Kind
  20068. * - BABYLON.VertexBuffer.UV4Kind
  20069. * - BABYLON.VertexBuffer.UV5Kind
  20070. * - BABYLON.VertexBuffer.UV6Kind
  20071. * - BABYLON.VertexBuffer.ColorKind
  20072. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20073. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20074. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20075. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20076. *
  20077. * Returns the Mesh.
  20078. */
  20079. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20080. if (!this._geometry) {
  20081. return;
  20082. }
  20083. if (!makeItUnique) {
  20084. this._geometry.updateVerticesData(kind, data, updateExtends);
  20085. }
  20086. else {
  20087. this.makeGeometryUnique();
  20088. this.updateVerticesData(kind, data, updateExtends, false);
  20089. }
  20090. return this;
  20091. };
  20092. /**
  20093. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  20094. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  20095. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  20096. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  20097. * Returns the Mesh.
  20098. */
  20099. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  20100. if (computeNormals === void 0) { computeNormals = true; }
  20101. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20102. positionFunction(positions);
  20103. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  20104. if (computeNormals) {
  20105. var indices = this.getIndices();
  20106. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20107. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20108. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  20109. }
  20110. return this;
  20111. };
  20112. /**
  20113. * Creates a un-shared specific occurence of the geometry for the mesh.
  20114. * Returns the Mesh.
  20115. */
  20116. Mesh.prototype.makeGeometryUnique = function () {
  20117. if (!this._geometry) {
  20118. return;
  20119. }
  20120. var oldGeometry = this._geometry;
  20121. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  20122. oldGeometry.releaseForMesh(this, true);
  20123. geometry.applyToMesh(this);
  20124. return this;
  20125. };
  20126. /**
  20127. * Sets the mesh indices.
  20128. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  20129. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20130. * This method creates a new index buffer each call.
  20131. * Returns the Mesh.
  20132. */
  20133. Mesh.prototype.setIndices = function (indices, totalVertices) {
  20134. if (!this._geometry) {
  20135. var vertexData = new BABYLON.VertexData();
  20136. vertexData.indices = indices;
  20137. var scene = this.getScene();
  20138. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  20139. }
  20140. else {
  20141. this._geometry.setIndices(indices, totalVertices);
  20142. }
  20143. return this;
  20144. };
  20145. /**
  20146. * Invert the geometry to move from a right handed system to a left handed one.
  20147. * Returns the Mesh.
  20148. */
  20149. Mesh.prototype.toLeftHanded = function () {
  20150. if (!this._geometry) {
  20151. return;
  20152. }
  20153. this._geometry.toLeftHanded();
  20154. return this;
  20155. };
  20156. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  20157. var engine = this.getScene().getEngine();
  20158. // Wireframe
  20159. var indexToBind;
  20160. if (this._unIndexed) {
  20161. indexToBind = null;
  20162. }
  20163. else {
  20164. switch (fillMode) {
  20165. case BABYLON.Material.PointFillMode:
  20166. indexToBind = null;
  20167. break;
  20168. case BABYLON.Material.WireFrameFillMode:
  20169. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  20170. break;
  20171. default:
  20172. case BABYLON.Material.TriangleFillMode:
  20173. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  20174. break;
  20175. }
  20176. }
  20177. // VBOs
  20178. this._geometry._bind(effect, indexToBind);
  20179. return this;
  20180. };
  20181. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  20182. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20183. return this;
  20184. }
  20185. this.onBeforeDrawObservable.notifyObservers(this);
  20186. var engine = this.getScene().getEngine();
  20187. // Draw order
  20188. switch (fillMode) {
  20189. case BABYLON.Material.PointFillMode:
  20190. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20191. break;
  20192. case BABYLON.Material.WireFrameFillMode:
  20193. if (this._unIndexed) {
  20194. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20195. }
  20196. else {
  20197. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  20198. }
  20199. break;
  20200. default:
  20201. if (this._unIndexed) {
  20202. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20203. }
  20204. else {
  20205. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  20206. }
  20207. }
  20208. return this;
  20209. };
  20210. /**
  20211. * Registers for this mesh a javascript function called just before the rendering process.
  20212. * This function is passed the current mesh.
  20213. * Return the Mesh.
  20214. */
  20215. Mesh.prototype.registerBeforeRender = function (func) {
  20216. this.onBeforeRenderObservable.add(func);
  20217. return this;
  20218. };
  20219. /**
  20220. * Disposes a previously registered javascript function called before the rendering.
  20221. * This function is passed the current mesh.
  20222. * Returns the Mesh.
  20223. */
  20224. Mesh.prototype.unregisterBeforeRender = function (func) {
  20225. this.onBeforeRenderObservable.removeCallback(func);
  20226. return this;
  20227. };
  20228. /**
  20229. * Registers for this mesh a javascript function called just after the rendering is complete.
  20230. * This function is passed the current mesh.
  20231. * Returns the Mesh.
  20232. */
  20233. Mesh.prototype.registerAfterRender = function (func) {
  20234. this.onAfterRenderObservable.add(func);
  20235. return this;
  20236. };
  20237. /**
  20238. * Disposes a previously registered javascript function called after the rendering.
  20239. * This function is passed the current mesh.
  20240. * Return the Mesh.
  20241. */
  20242. Mesh.prototype.unregisterAfterRender = function (func) {
  20243. this.onAfterRenderObservable.removeCallback(func);
  20244. return this;
  20245. };
  20246. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  20247. var scene = this.getScene();
  20248. this._batchCache.mustReturn = false;
  20249. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  20250. this._batchCache.visibleInstances[subMeshId] = null;
  20251. if (this._visibleInstances) {
  20252. var currentRenderId = scene.getRenderId();
  20253. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  20254. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  20255. var selfRenderId = this._renderId;
  20256. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  20257. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  20258. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  20259. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  20260. }
  20261. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  20262. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  20263. this._batchCache.mustReturn = true;
  20264. return this._batchCache;
  20265. }
  20266. if (currentRenderId !== selfRenderId) {
  20267. this._batchCache.renderSelf[subMeshId] = false;
  20268. }
  20269. }
  20270. this._renderIdForInstances[subMeshId] = currentRenderId;
  20271. }
  20272. return this._batchCache;
  20273. };
  20274. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  20275. var visibleInstances = batch.visibleInstances[subMesh._id];
  20276. var matricesCount = visibleInstances.length + 1;
  20277. var bufferSize = matricesCount * 16 * 4;
  20278. var currentInstancesBufferSize = this._instancesBufferSize;
  20279. var instancesBuffer = this._instancesBuffer;
  20280. while (this._instancesBufferSize < bufferSize) {
  20281. this._instancesBufferSize *= 2;
  20282. }
  20283. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  20284. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  20285. }
  20286. var offset = 0;
  20287. var instancesCount = 0;
  20288. var world = this.getWorldMatrix();
  20289. if (batch.renderSelf[subMesh._id]) {
  20290. world.copyToArray(this._instancesData, offset);
  20291. offset += 16;
  20292. instancesCount++;
  20293. }
  20294. if (visibleInstances) {
  20295. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  20296. var instance = visibleInstances[instanceIndex];
  20297. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  20298. offset += 16;
  20299. instancesCount++;
  20300. }
  20301. }
  20302. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  20303. if (instancesBuffer) {
  20304. instancesBuffer.dispose();
  20305. }
  20306. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  20307. this._instancesBuffer = instancesBuffer;
  20308. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  20309. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  20310. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  20311. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  20312. }
  20313. else {
  20314. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  20315. }
  20316. this.geometry._bind(effect);
  20317. this._draw(subMesh, fillMode, instancesCount);
  20318. engine.unbindInstanceAttributes();
  20319. return this;
  20320. };
  20321. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  20322. var scene = this.getScene();
  20323. var engine = scene.getEngine();
  20324. if (hardwareInstancedRendering) {
  20325. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  20326. }
  20327. else {
  20328. if (batch.renderSelf[subMesh._id]) {
  20329. // Draw
  20330. if (onBeforeDraw) {
  20331. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  20332. }
  20333. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  20334. }
  20335. if (batch.visibleInstances[subMesh._id]) {
  20336. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20337. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20338. // World
  20339. var world = instance.getWorldMatrix();
  20340. if (onBeforeDraw) {
  20341. onBeforeDraw(true, world, effectiveMaterial);
  20342. }
  20343. // Draw
  20344. this._draw(subMesh, fillMode);
  20345. }
  20346. }
  20347. }
  20348. return this;
  20349. };
  20350. /**
  20351. * Triggers the draw call for the mesh.
  20352. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  20353. * Returns the Mesh.
  20354. */
  20355. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  20356. var scene = this.getScene();
  20357. // Managing instances
  20358. var batch = this._getInstancesRenderList(subMesh._id);
  20359. if (batch.mustReturn) {
  20360. return this;
  20361. }
  20362. // Checking geometry state
  20363. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20364. return this;
  20365. }
  20366. var callbackIndex;
  20367. this.onBeforeRenderObservable.notifyObservers(this);
  20368. var engine = scene.getEngine();
  20369. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  20370. // Material
  20371. var effectiveMaterial = subMesh.getMaterial();
  20372. if (!effectiveMaterial) {
  20373. return this;
  20374. }
  20375. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20376. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  20377. return this;
  20378. }
  20379. }
  20380. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  20381. return this;
  20382. }
  20383. // Alpha mode
  20384. if (enableAlphaMode) {
  20385. engine.setAlphaMode(effectiveMaterial.alphaMode);
  20386. }
  20387. // Outline - step 1
  20388. var savedDepthWrite = engine.getDepthWrite();
  20389. if (this.renderOutline) {
  20390. engine.setDepthWrite(false);
  20391. scene.getOutlineRenderer().render(subMesh, batch);
  20392. engine.setDepthWrite(savedDepthWrite);
  20393. }
  20394. var effect;
  20395. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20396. effect = subMesh.effect;
  20397. }
  20398. else {
  20399. effect = effectiveMaterial.getEffect();
  20400. }
  20401. effectiveMaterial._preBind(effect);
  20402. // Bind
  20403. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  20404. this._bind(subMesh, effect, fillMode);
  20405. var world = this.getWorldMatrix();
  20406. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20407. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  20408. }
  20409. else {
  20410. effectiveMaterial.bind(world, this);
  20411. }
  20412. // Draw
  20413. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  20414. // Unbind
  20415. effectiveMaterial.unbind();
  20416. // Outline - step 2
  20417. if (this.renderOutline && savedDepthWrite) {
  20418. engine.setDepthWrite(true);
  20419. engine.setColorWrite(false);
  20420. scene.getOutlineRenderer().render(subMesh, batch);
  20421. engine.setColorWrite(true);
  20422. }
  20423. // Overlay
  20424. if (this.renderOverlay) {
  20425. var currentMode = engine.getAlphaMode();
  20426. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20427. scene.getOutlineRenderer().render(subMesh, batch, true);
  20428. engine.setAlphaMode(currentMode);
  20429. }
  20430. this.onAfterRenderObservable.notifyObservers(this);
  20431. return this;
  20432. };
  20433. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  20434. if (isInstance) {
  20435. effectiveMaterial.bindOnlyWorldMatrix(world);
  20436. }
  20437. return this;
  20438. };
  20439. /**
  20440. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  20441. */
  20442. Mesh.prototype.getEmittedParticleSystems = function () {
  20443. var results = new Array();
  20444. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20445. var particleSystem = this.getScene().particleSystems[index];
  20446. if (particleSystem.emitter === this) {
  20447. results.push(particleSystem);
  20448. }
  20449. }
  20450. return results;
  20451. };
  20452. /**
  20453. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  20454. */
  20455. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  20456. var results = new Array();
  20457. var descendants = this.getDescendants();
  20458. descendants.push(this);
  20459. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20460. var particleSystem = this.getScene().particleSystems[index];
  20461. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  20462. results.push(particleSystem);
  20463. }
  20464. }
  20465. return results;
  20466. };
  20467. Mesh.prototype._checkDelayState = function () {
  20468. var scene = this.getScene();
  20469. if (this._geometry) {
  20470. this._geometry.load(scene);
  20471. }
  20472. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20473. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  20474. this._queueLoad(this, scene);
  20475. }
  20476. return this;
  20477. };
  20478. Mesh.prototype._queueLoad = function (mesh, scene) {
  20479. var _this = this;
  20480. scene._addPendingData(mesh);
  20481. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  20482. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  20483. if (data instanceof ArrayBuffer) {
  20484. _this._delayLoadingFunction(data, _this);
  20485. }
  20486. else {
  20487. _this._delayLoadingFunction(JSON.parse(data), _this);
  20488. }
  20489. _this.instances.forEach(function (instance) {
  20490. instance._syncSubMeshes();
  20491. });
  20492. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20493. scene._removePendingData(_this);
  20494. }, function () { }, scene.database, getBinaryData);
  20495. return this;
  20496. };
  20497. /**
  20498. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  20499. */
  20500. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  20501. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20502. return false;
  20503. }
  20504. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  20505. return false;
  20506. }
  20507. this._checkDelayState();
  20508. return true;
  20509. };
  20510. /**
  20511. * Sets the mesh material by the material or multiMaterial `id` property.
  20512. * The material `id` is a string identifying the material or the multiMaterial.
  20513. * This method returns the Mesh.
  20514. */
  20515. Mesh.prototype.setMaterialByID = function (id) {
  20516. var materials = this.getScene().materials;
  20517. var index;
  20518. for (index = materials.length - 1; index > -1; index--) {
  20519. if (materials[index].id === id) {
  20520. this.material = materials[index];
  20521. return this;
  20522. }
  20523. }
  20524. // Multi
  20525. var multiMaterials = this.getScene().multiMaterials;
  20526. for (index = multiMaterials.length - 1; index > -1; index--) {
  20527. if (multiMaterials[index].id === id) {
  20528. this.material = multiMaterials[index];
  20529. return this;
  20530. }
  20531. }
  20532. return this;
  20533. };
  20534. /**
  20535. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  20536. */
  20537. Mesh.prototype.getAnimatables = function () {
  20538. var results = [];
  20539. if (this.material) {
  20540. results.push(this.material);
  20541. }
  20542. if (this.skeleton) {
  20543. results.push(this.skeleton);
  20544. }
  20545. return results;
  20546. };
  20547. /**
  20548. * Modifies the mesh geometry according to the passed transformation matrix.
  20549. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  20550. * The mesh normals are modified accordingly the same transformation.
  20551. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20552. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20553. * Returns the Mesh.
  20554. */
  20555. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  20556. // Position
  20557. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20558. return this;
  20559. }
  20560. var submeshes = this.subMeshes.splice(0);
  20561. this._resetPointsArrayCache();
  20562. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20563. var temp = [];
  20564. var index;
  20565. for (index = 0; index < data.length; index += 3) {
  20566. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  20567. }
  20568. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  20569. // Normals
  20570. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20571. return this;
  20572. }
  20573. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20574. temp = [];
  20575. for (index = 0; index < data.length; index += 3) {
  20576. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  20577. }
  20578. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  20579. // flip faces?
  20580. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  20581. this.flipFaces();
  20582. }
  20583. // Restore submeshes
  20584. this.releaseSubMeshes();
  20585. this.subMeshes = submeshes;
  20586. return this;
  20587. };
  20588. /**
  20589. * Modifies the mesh geometry according to its own current World Matrix.
  20590. * The mesh World Matrix is then reset.
  20591. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  20592. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20593. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20594. * Returns the Mesh.
  20595. */
  20596. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  20597. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  20598. this.scaling.copyFromFloats(1, 1, 1);
  20599. this.position.copyFromFloats(0, 0, 0);
  20600. this.rotation.copyFromFloats(0, 0, 0);
  20601. //only if quaternion is already set
  20602. if (this.rotationQuaternion) {
  20603. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  20604. }
  20605. this._worldMatrix = BABYLON.Matrix.Identity();
  20606. return this;
  20607. };
  20608. Object.defineProperty(Mesh.prototype, "_positions", {
  20609. // Cache
  20610. get: function () {
  20611. if (this._geometry) {
  20612. return this._geometry._positions;
  20613. }
  20614. return null;
  20615. },
  20616. enumerable: true,
  20617. configurable: true
  20618. });
  20619. Mesh.prototype._resetPointsArrayCache = function () {
  20620. if (this._geometry) {
  20621. this._geometry._resetPointsArrayCache();
  20622. }
  20623. return this;
  20624. };
  20625. Mesh.prototype._generatePointsArray = function () {
  20626. if (this._geometry) {
  20627. return this._geometry._generatePointsArray();
  20628. }
  20629. return false;
  20630. };
  20631. /**
  20632. * Returns a new Mesh object generated from the current mesh properties.
  20633. * This method must not get confused with createInstance().
  20634. * The parameter `name` is a string, the name given to the new mesh.
  20635. * The optional parameter `newParent` can be any Node object (default `null`).
  20636. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  20637. * 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.
  20638. */
  20639. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  20640. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20641. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  20642. };
  20643. /**
  20644. * Disposes the mesh.
  20645. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  20646. */
  20647. Mesh.prototype.dispose = function (doNotRecurse) {
  20648. var _this = this;
  20649. this.morphTargetManager = undefined;
  20650. if (this._geometry) {
  20651. this._geometry.releaseForMesh(this, true);
  20652. }
  20653. // Sources
  20654. var meshes = this.getScene().meshes;
  20655. meshes.forEach(function (mesh) {
  20656. if (mesh._source && mesh._source === _this) {
  20657. mesh._source = null;
  20658. }
  20659. });
  20660. this._source = null;
  20661. // Instances
  20662. if (this._instancesBuffer) {
  20663. this._instancesBuffer.dispose();
  20664. this._instancesBuffer = null;
  20665. }
  20666. while (this.instances.length) {
  20667. this.instances[0].dispose();
  20668. }
  20669. // Highlight layers.
  20670. var highlightLayers = this.getScene().highlightLayers;
  20671. for (var i = 0; i < highlightLayers.length; i++) {
  20672. var highlightLayer = highlightLayers[i];
  20673. if (highlightLayer) {
  20674. highlightLayer.removeMesh(this);
  20675. highlightLayer.removeExcludedMesh(this);
  20676. }
  20677. }
  20678. _super.prototype.dispose.call(this, doNotRecurse);
  20679. };
  20680. /**
  20681. * Modifies the mesh geometry according to a displacement map.
  20682. * 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.
  20683. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20684. * This method returns nothing.
  20685. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  20686. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20687. * 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.
  20688. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  20689. * The parameter `uvScale` is an optional vector2 used to scale UV.
  20690. *
  20691. * Returns the Mesh.
  20692. */
  20693. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  20694. var _this = this;
  20695. var scene = this.getScene();
  20696. var onload = function (img) {
  20697. // Getting height map data
  20698. var canvas = document.createElement("canvas");
  20699. var context = canvas.getContext("2d");
  20700. var heightMapWidth = img.width;
  20701. var heightMapHeight = img.height;
  20702. canvas.width = heightMapWidth;
  20703. canvas.height = heightMapHeight;
  20704. context.drawImage(img, 0, 0);
  20705. // Create VertexData from map data
  20706. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20707. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  20708. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  20709. //execute success callback, if set
  20710. if (onSuccess) {
  20711. onSuccess(_this);
  20712. }
  20713. };
  20714. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20715. return this;
  20716. };
  20717. /**
  20718. * Modifies the mesh geometry according to a displacementMap buffer.
  20719. * 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.
  20720. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20721. * This method returns nothing.
  20722. * 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.
  20723. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  20724. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20725. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  20726. * The parameter `uvScale` is an optional vector2 used to scale UV.
  20727. *
  20728. * Returns the Mesh.
  20729. */
  20730. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  20731. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  20732. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  20733. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20734. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  20735. return this;
  20736. }
  20737. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20738. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20739. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20740. var position = BABYLON.Vector3.Zero();
  20741. var normal = BABYLON.Vector3.Zero();
  20742. var uv = BABYLON.Vector2.Zero();
  20743. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  20744. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  20745. for (var index = 0; index < positions.length; index += 3) {
  20746. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  20747. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  20748. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  20749. // Compute height
  20750. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  20751. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  20752. var pos = (u + v * heightMapWidth) * 4;
  20753. var r = buffer[pos] / 255.0;
  20754. var g = buffer[pos + 1] / 255.0;
  20755. var b = buffer[pos + 2] / 255.0;
  20756. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20757. normal.normalize();
  20758. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  20759. position = position.add(normal);
  20760. position.toArray(positions, index);
  20761. }
  20762. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  20763. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  20764. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20765. return this;
  20766. };
  20767. /**
  20768. * Modify the mesh to get a flat shading rendering.
  20769. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  20770. * This method returns the Mesh.
  20771. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  20772. */
  20773. Mesh.prototype.convertToFlatShadedMesh = function () {
  20774. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  20775. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20776. var kinds = this.getVerticesDataKinds();
  20777. var vbs = [];
  20778. var data = [];
  20779. var newdata = [];
  20780. var updatableNormals = false;
  20781. var kindIndex;
  20782. var kind;
  20783. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20784. kind = kinds[kindIndex];
  20785. var vertexBuffer = this.getVertexBuffer(kind);
  20786. if (kind === BABYLON.VertexBuffer.NormalKind) {
  20787. updatableNormals = vertexBuffer.isUpdatable();
  20788. kinds.splice(kindIndex, 1);
  20789. kindIndex--;
  20790. continue;
  20791. }
  20792. vbs[kind] = vertexBuffer;
  20793. data[kind] = vbs[kind].getData();
  20794. newdata[kind] = [];
  20795. }
  20796. // Save previous submeshes
  20797. var previousSubmeshes = this.subMeshes.slice(0);
  20798. var indices = this.getIndices();
  20799. var totalIndices = this.getTotalIndices();
  20800. // Generating unique vertices per face
  20801. var index;
  20802. for (index = 0; index < totalIndices; index++) {
  20803. var vertexIndex = indices[index];
  20804. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20805. kind = kinds[kindIndex];
  20806. var stride = vbs[kind].getStrideSize();
  20807. for (var offset = 0; offset < stride; offset++) {
  20808. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20809. }
  20810. }
  20811. }
  20812. // Updating faces & normal
  20813. var normals = [];
  20814. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  20815. for (index = 0; index < totalIndices; index += 3) {
  20816. indices[index] = index;
  20817. indices[index + 1] = index + 1;
  20818. indices[index + 2] = index + 2;
  20819. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  20820. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  20821. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  20822. var p1p2 = p1.subtract(p2);
  20823. var p3p2 = p3.subtract(p2);
  20824. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20825. // Store same normals for every vertex
  20826. for (var localIndex = 0; localIndex < 3; localIndex++) {
  20827. normals.push(normal.x);
  20828. normals.push(normal.y);
  20829. normals.push(normal.z);
  20830. }
  20831. }
  20832. this.setIndices(indices);
  20833. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  20834. // Updating vertex buffers
  20835. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20836. kind = kinds[kindIndex];
  20837. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20838. }
  20839. // Updating submeshes
  20840. this.releaseSubMeshes();
  20841. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20842. var previousOne = previousSubmeshes[submeshIndex];
  20843. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20844. }
  20845. this.synchronizeInstances();
  20846. return this;
  20847. };
  20848. /**
  20849. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  20850. * In other words, more vertices, no more indices and a single bigger VBO.
  20851. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  20852. * Returns the Mesh.
  20853. */
  20854. Mesh.prototype.convertToUnIndexedMesh = function () {
  20855. /// <summary>Remove indices by unfolding faces into buffers</summary>
  20856. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20857. var kinds = this.getVerticesDataKinds();
  20858. var vbs = [];
  20859. var data = [];
  20860. var newdata = [];
  20861. var updatableNormals = false;
  20862. var kindIndex;
  20863. var kind;
  20864. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20865. kind = kinds[kindIndex];
  20866. var vertexBuffer = this.getVertexBuffer(kind);
  20867. vbs[kind] = vertexBuffer;
  20868. data[kind] = vbs[kind].getData();
  20869. newdata[kind] = [];
  20870. }
  20871. // Save previous submeshes
  20872. var previousSubmeshes = this.subMeshes.slice(0);
  20873. var indices = this.getIndices();
  20874. var totalIndices = this.getTotalIndices();
  20875. // Generating unique vertices per face
  20876. var index;
  20877. for (index = 0; index < totalIndices; index++) {
  20878. var vertexIndex = indices[index];
  20879. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20880. kind = kinds[kindIndex];
  20881. var stride = vbs[kind].getStrideSize();
  20882. for (var offset = 0; offset < stride; offset++) {
  20883. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20884. }
  20885. }
  20886. }
  20887. // Updating indices
  20888. for (index = 0; index < totalIndices; index += 3) {
  20889. indices[index] = index;
  20890. indices[index + 1] = index + 1;
  20891. indices[index + 2] = index + 2;
  20892. }
  20893. this.setIndices(indices);
  20894. // Updating vertex buffers
  20895. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20896. kind = kinds[kindIndex];
  20897. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20898. }
  20899. // Updating submeshes
  20900. this.releaseSubMeshes();
  20901. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20902. var previousOne = previousSubmeshes[submeshIndex];
  20903. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20904. }
  20905. this._unIndexed = true;
  20906. this.synchronizeInstances();
  20907. return this;
  20908. };
  20909. /**
  20910. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  20911. * This method returns the Mesh.
  20912. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  20913. */
  20914. Mesh.prototype.flipFaces = function (flipNormals) {
  20915. if (flipNormals === void 0) { flipNormals = false; }
  20916. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  20917. var i;
  20918. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20919. for (i = 0; i < vertex_data.normals.length; i++) {
  20920. vertex_data.normals[i] *= -1;
  20921. }
  20922. }
  20923. var temp;
  20924. for (i = 0; i < vertex_data.indices.length; i += 3) {
  20925. // reassign indices
  20926. temp = vertex_data.indices[i + 1];
  20927. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  20928. vertex_data.indices[i + 2] = temp;
  20929. }
  20930. vertex_data.applyToMesh(this);
  20931. return this;
  20932. };
  20933. // Instances
  20934. /**
  20935. * Creates a new InstancedMesh object from the mesh model.
  20936. * An instance shares the same properties and the same material than its model.
  20937. * Only these properties of each instance can then be set individually :
  20938. * - position
  20939. * - rotation
  20940. * - rotationQuaternion
  20941. * - setPivotMatrix
  20942. * - scaling
  20943. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  20944. * Warning : this method is not supported for Line mesh and LineSystem
  20945. */
  20946. Mesh.prototype.createInstance = function (name) {
  20947. return new BABYLON.InstancedMesh(name, this);
  20948. };
  20949. /**
  20950. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  20951. * After this call, all the mesh instances have the same submeshes than the current mesh.
  20952. * This method returns the Mesh.
  20953. */
  20954. Mesh.prototype.synchronizeInstances = function () {
  20955. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  20956. var instance = this.instances[instanceIndex];
  20957. instance._syncSubMeshes();
  20958. }
  20959. return this;
  20960. };
  20961. /**
  20962. * Simplify the mesh according to the given array of settings.
  20963. * Function will return immediately and will simplify async. It returns the Mesh.
  20964. * @param settings a collection of simplification settings.
  20965. * @param parallelProcessing should all levels calculate parallel or one after the other.
  20966. * @param type the type of simplification to run.
  20967. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  20968. */
  20969. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  20970. if (parallelProcessing === void 0) { parallelProcessing = true; }
  20971. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  20972. this.getScene().simplificationQueue.addTask({
  20973. settings: settings,
  20974. parallelProcessing: parallelProcessing,
  20975. mesh: this,
  20976. simplificationType: simplificationType,
  20977. successCallback: successCallback
  20978. });
  20979. return this;
  20980. };
  20981. /**
  20982. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  20983. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  20984. * This should be used together with the simplification to avoid disappearing triangles.
  20985. * Returns the Mesh.
  20986. * @param successCallback an optional success callback to be called after the optimization finished.
  20987. */
  20988. Mesh.prototype.optimizeIndices = function (successCallback) {
  20989. var _this = this;
  20990. var indices = this.getIndices();
  20991. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20992. var vectorPositions = [];
  20993. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  20994. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  20995. }
  20996. var dupes = [];
  20997. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  20998. var realPos = vectorPositions.length - 1 - iteration;
  20999. var testedPosition = vectorPositions[realPos];
  21000. for (var j = 0; j < realPos; ++j) {
  21001. var againstPosition = vectorPositions[j];
  21002. if (testedPosition.equals(againstPosition)) {
  21003. dupes[realPos] = j;
  21004. break;
  21005. }
  21006. }
  21007. }, function () {
  21008. for (var i = 0; i < indices.length; ++i) {
  21009. indices[i] = dupes[indices[i]] || indices[i];
  21010. }
  21011. //indices are now reordered
  21012. var originalSubMeshes = _this.subMeshes.slice(0);
  21013. _this.setIndices(indices);
  21014. _this.subMeshes = originalSubMeshes;
  21015. if (successCallback) {
  21016. successCallback(_this);
  21017. }
  21018. });
  21019. return this;
  21020. };
  21021. Mesh.prototype.serialize = function (serializationObject) {
  21022. serializationObject.name = this.name;
  21023. serializationObject.id = this.id;
  21024. serializationObject.type = this.getClassName();
  21025. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  21026. serializationObject.tags = BABYLON.Tags.GetTags(this);
  21027. }
  21028. serializationObject.position = this.position.asArray();
  21029. if (this.rotationQuaternion) {
  21030. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  21031. }
  21032. else if (this.rotation) {
  21033. serializationObject.rotation = this.rotation.asArray();
  21034. }
  21035. serializationObject.scaling = this.scaling.asArray();
  21036. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  21037. serializationObject.isEnabled = this.isEnabled();
  21038. serializationObject.isVisible = this.isVisible;
  21039. serializationObject.infiniteDistance = this.infiniteDistance;
  21040. serializationObject.pickable = this.isPickable;
  21041. serializationObject.receiveShadows = this.receiveShadows;
  21042. serializationObject.billboardMode = this.billboardMode;
  21043. serializationObject.visibility = this.visibility;
  21044. serializationObject.checkCollisions = this.checkCollisions;
  21045. serializationObject.isBlocker = this.isBlocker;
  21046. // Parent
  21047. if (this.parent) {
  21048. serializationObject.parentId = this.parent.id;
  21049. }
  21050. // Geometry
  21051. var geometry = this._geometry;
  21052. if (geometry) {
  21053. var geometryId = geometry.id;
  21054. serializationObject.geometryId = geometryId;
  21055. // SubMeshes
  21056. serializationObject.subMeshes = [];
  21057. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  21058. var subMesh = this.subMeshes[subIndex];
  21059. serializationObject.subMeshes.push({
  21060. materialIndex: subMesh.materialIndex,
  21061. verticesStart: subMesh.verticesStart,
  21062. verticesCount: subMesh.verticesCount,
  21063. indexStart: subMesh.indexStart,
  21064. indexCount: subMesh.indexCount
  21065. });
  21066. }
  21067. }
  21068. // Material
  21069. if (this.material) {
  21070. serializationObject.materialId = this.material.id;
  21071. }
  21072. else {
  21073. this.material = null;
  21074. }
  21075. // Morph targets
  21076. if (this.morphTargetManager) {
  21077. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  21078. }
  21079. // Skeleton
  21080. if (this.skeleton) {
  21081. serializationObject.skeletonId = this.skeleton.id;
  21082. }
  21083. // Physics
  21084. //TODO implement correct serialization for physics impostors.
  21085. if (this.getPhysicsImpostor()) {
  21086. var impostor = this.getPhysicsImpostor();
  21087. serializationObject.physicsMass = impostor.getParam("mass");
  21088. serializationObject.physicsFriction = impostor.getParam("friction");
  21089. serializationObject.physicsRestitution = impostor.getParam("mass");
  21090. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  21091. }
  21092. // Metadata
  21093. if (this.metadata) {
  21094. serializationObject.metadata = this.metadata;
  21095. }
  21096. // Instances
  21097. serializationObject.instances = [];
  21098. for (var index = 0; index < this.instances.length; index++) {
  21099. var instance = this.instances[index];
  21100. var serializationInstance = {
  21101. name: instance.name,
  21102. position: instance.position.asArray(),
  21103. scaling: instance.scaling.asArray()
  21104. };
  21105. if (instance.rotationQuaternion) {
  21106. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  21107. }
  21108. else if (instance.rotation) {
  21109. serializationInstance.rotation = instance.rotation.asArray();
  21110. }
  21111. serializationObject.instances.push(serializationInstance);
  21112. // Animations
  21113. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  21114. serializationInstance.ranges = instance.serializeAnimationRanges();
  21115. }
  21116. //
  21117. // Animations
  21118. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21119. serializationObject.ranges = this.serializeAnimationRanges();
  21120. // Layer mask
  21121. serializationObject.layerMask = this.layerMask;
  21122. // Alpha
  21123. serializationObject.alphaIndex = this.alphaIndex;
  21124. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  21125. // Overlay
  21126. serializationObject.overlayAlpha = this.overlayAlpha;
  21127. serializationObject.overlayColor = this.overlayColor.asArray();
  21128. serializationObject.renderOverlay = this.renderOverlay;
  21129. // Fog
  21130. serializationObject.applyFog = this.applyFog;
  21131. // Action Manager
  21132. if (this.actionManager) {
  21133. serializationObject.actions = this.actionManager.serialize(this.name);
  21134. }
  21135. };
  21136. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  21137. if (!this.geometry) {
  21138. return;
  21139. }
  21140. this._markSubMeshesAsAttributesDirty();
  21141. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  21142. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  21143. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  21144. this.morphTargetManager = undefined;
  21145. return;
  21146. }
  21147. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  21148. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  21149. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  21150. if (morphTarget.hasNormals) {
  21151. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  21152. }
  21153. if (morphTarget.hasTangents) {
  21154. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  21155. }
  21156. }
  21157. }
  21158. else {
  21159. var index = 0;
  21160. // Positions
  21161. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  21162. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  21163. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  21164. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  21165. }
  21166. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  21167. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  21168. }
  21169. index++;
  21170. }
  21171. }
  21172. };
  21173. // Statics
  21174. /**
  21175. * Returns a new Mesh object what is a deep copy of the passed mesh.
  21176. * The parameter `parsedMesh` is the mesh to be copied.
  21177. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  21178. */
  21179. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  21180. var mesh;
  21181. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  21182. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  21183. }
  21184. else {
  21185. mesh = new Mesh(parsedMesh.name, scene);
  21186. }
  21187. mesh.id = parsedMesh.id;
  21188. if (BABYLON.Tags) {
  21189. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  21190. }
  21191. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  21192. if (parsedMesh.metadata !== undefined) {
  21193. mesh.metadata = parsedMesh.metadata;
  21194. }
  21195. if (parsedMesh.rotationQuaternion) {
  21196. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  21197. }
  21198. else if (parsedMesh.rotation) {
  21199. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  21200. }
  21201. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  21202. if (parsedMesh.localMatrix) {
  21203. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  21204. }
  21205. else if (parsedMesh.pivotMatrix) {
  21206. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  21207. }
  21208. mesh.setEnabled(parsedMesh.isEnabled);
  21209. mesh.isVisible = parsedMesh.isVisible;
  21210. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  21211. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  21212. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  21213. if (parsedMesh.applyFog !== undefined) {
  21214. mesh.applyFog = parsedMesh.applyFog;
  21215. }
  21216. if (parsedMesh.pickable !== undefined) {
  21217. mesh.isPickable = parsedMesh.pickable;
  21218. }
  21219. if (parsedMesh.alphaIndex !== undefined) {
  21220. mesh.alphaIndex = parsedMesh.alphaIndex;
  21221. }
  21222. mesh.receiveShadows = parsedMesh.receiveShadows;
  21223. mesh.billboardMode = parsedMesh.billboardMode;
  21224. if (parsedMesh.visibility !== undefined) {
  21225. mesh.visibility = parsedMesh.visibility;
  21226. }
  21227. mesh.checkCollisions = parsedMesh.checkCollisions;
  21228. if (parsedMesh.isBlocker !== undefined) {
  21229. mesh.isBlocker = parsedMesh.isBlocker;
  21230. }
  21231. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  21232. // freezeWorldMatrix
  21233. if (parsedMesh.freezeWorldMatrix) {
  21234. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  21235. }
  21236. // Parent
  21237. if (parsedMesh.parentId) {
  21238. mesh._waitingParentId = parsedMesh.parentId;
  21239. }
  21240. // Actions
  21241. if (parsedMesh.actions !== undefined) {
  21242. mesh._waitingActions = parsedMesh.actions;
  21243. }
  21244. // Overlay
  21245. if (parsedMesh.overlayAlpha !== undefined) {
  21246. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  21247. }
  21248. if (parsedMesh.overlayColor !== undefined) {
  21249. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  21250. }
  21251. if (parsedMesh.renderOverlay !== undefined) {
  21252. mesh.renderOverlay = parsedMesh.renderOverlay;
  21253. }
  21254. // Geometry
  21255. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  21256. if (parsedMesh.delayLoadingFile) {
  21257. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21258. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  21259. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  21260. if (parsedMesh._binaryInfo) {
  21261. mesh._binaryInfo = parsedMesh._binaryInfo;
  21262. }
  21263. mesh._delayInfo = [];
  21264. if (parsedMesh.hasUVs) {
  21265. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  21266. }
  21267. if (parsedMesh.hasUVs2) {
  21268. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  21269. }
  21270. if (parsedMesh.hasUVs3) {
  21271. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  21272. }
  21273. if (parsedMesh.hasUVs4) {
  21274. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  21275. }
  21276. if (parsedMesh.hasUVs5) {
  21277. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  21278. }
  21279. if (parsedMesh.hasUVs6) {
  21280. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  21281. }
  21282. if (parsedMesh.hasColors) {
  21283. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  21284. }
  21285. if (parsedMesh.hasMatricesIndices) {
  21286. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  21287. }
  21288. if (parsedMesh.hasMatricesWeights) {
  21289. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  21290. }
  21291. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  21292. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  21293. mesh._checkDelayState();
  21294. }
  21295. }
  21296. else {
  21297. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  21298. }
  21299. // Material
  21300. if (parsedMesh.materialId) {
  21301. mesh.setMaterialByID(parsedMesh.materialId);
  21302. }
  21303. else {
  21304. mesh.material = null;
  21305. }
  21306. // Morph targets
  21307. if (parsedMesh.morphTargetManagerId > -1) {
  21308. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  21309. }
  21310. // Skeleton
  21311. if (parsedMesh.skeletonId > -1) {
  21312. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  21313. if (parsedMesh.numBoneInfluencers) {
  21314. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  21315. }
  21316. }
  21317. // Animations
  21318. if (parsedMesh.animations) {
  21319. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21320. var parsedAnimation = parsedMesh.animations[animationIndex];
  21321. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21322. }
  21323. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  21324. }
  21325. if (parsedMesh.autoAnimate) {
  21326. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  21327. }
  21328. // Layer Mask
  21329. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  21330. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  21331. }
  21332. else {
  21333. mesh.layerMask = 0x0FFFFFFF;
  21334. }
  21335. // Physics
  21336. if (parsedMesh.physicsImpostor) {
  21337. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  21338. mass: parsedMesh.physicsMass,
  21339. friction: parsedMesh.physicsFriction,
  21340. restitution: parsedMesh.physicsRestitution
  21341. }, scene);
  21342. }
  21343. // Instances
  21344. if (parsedMesh.instances) {
  21345. for (var index = 0; index < parsedMesh.instances.length; index++) {
  21346. var parsedInstance = parsedMesh.instances[index];
  21347. var instance = mesh.createInstance(parsedInstance.name);
  21348. if (BABYLON.Tags) {
  21349. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  21350. }
  21351. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  21352. if (parsedInstance.parentId) {
  21353. instance._waitingParentId = parsedInstance.parentId;
  21354. }
  21355. if (parsedInstance.rotationQuaternion) {
  21356. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  21357. }
  21358. else if (parsedInstance.rotation) {
  21359. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  21360. }
  21361. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  21362. instance.checkCollisions = mesh.checkCollisions;
  21363. if (parsedMesh.animations) {
  21364. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21365. parsedAnimation = parsedMesh.animations[animationIndex];
  21366. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21367. }
  21368. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  21369. }
  21370. }
  21371. }
  21372. return mesh;
  21373. };
  21374. /**
  21375. * Creates a ribbon mesh.
  21376. * Please consider using the same method from the MeshBuilder class instead.
  21377. * 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.
  21378. *
  21379. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21380. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21381. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21382. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21383. * 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.
  21384. * 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.
  21385. * 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
  21386. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21387. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21388. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21389. */
  21390. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  21391. return BABYLON.MeshBuilder.CreateRibbon(name, {
  21392. pathArray: pathArray,
  21393. closeArray: closeArray,
  21394. closePath: closePath,
  21395. offset: offset,
  21396. updatable: updatable,
  21397. sideOrientation: sideOrientation,
  21398. instance: instance
  21399. }, scene);
  21400. };
  21401. /**
  21402. * Creates a plane polygonal mesh. By default, this is a disc.
  21403. * Please consider using the same method from the MeshBuilder class instead.
  21404. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21405. * 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.
  21406. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21407. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21408. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21409. */
  21410. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  21411. var options = {
  21412. radius: radius,
  21413. tessellation: tessellation,
  21414. sideOrientation: sideOrientation,
  21415. updatable: updatable
  21416. };
  21417. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  21418. };
  21419. /**
  21420. * Creates a box mesh.
  21421. * Please consider using the same method from the MeshBuilder class instead.
  21422. * The parameter `size` sets the size (float) of each box side (default 1).
  21423. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21424. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21425. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21426. */
  21427. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  21428. var options = {
  21429. size: size,
  21430. sideOrientation: sideOrientation,
  21431. updatable: updatable
  21432. };
  21433. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  21434. };
  21435. /**
  21436. * Creates a sphere mesh.
  21437. * Please consider using the same method from the MeshBuilder class instead.
  21438. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  21439. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  21440. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21441. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21442. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21443. */
  21444. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  21445. var options = {
  21446. segments: segments,
  21447. diameterX: diameter,
  21448. diameterY: diameter,
  21449. diameterZ: diameter,
  21450. sideOrientation: sideOrientation,
  21451. updatable: updatable
  21452. };
  21453. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  21454. };
  21455. /**
  21456. * Creates a cylinder or a cone mesh.
  21457. * Please consider using the same method from the MeshBuilder class instead.
  21458. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21459. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21460. * 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.
  21461. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21462. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21463. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21464. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21465. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21466. */
  21467. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  21468. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  21469. if (scene !== undefined) {
  21470. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  21471. updatable = scene;
  21472. }
  21473. scene = subdivisions;
  21474. subdivisions = 1;
  21475. }
  21476. var options = {
  21477. height: height,
  21478. diameterTop: diameterTop,
  21479. diameterBottom: diameterBottom,
  21480. tessellation: tessellation,
  21481. subdivisions: subdivisions,
  21482. sideOrientation: sideOrientation,
  21483. updatable: updatable
  21484. };
  21485. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  21486. };
  21487. // Torus (Code from SharpDX.org)
  21488. /**
  21489. * Creates a torus mesh.
  21490. * Please consider using the same method from the MeshBuilder class instead.
  21491. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21492. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21493. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21494. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21495. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21496. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21497. */
  21498. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  21499. var options = {
  21500. diameter: diameter,
  21501. thickness: thickness,
  21502. tessellation: tessellation,
  21503. sideOrientation: sideOrientation,
  21504. updatable: updatable
  21505. };
  21506. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  21507. };
  21508. /**
  21509. * Creates a torus knot mesh.
  21510. * Please consider using the same method from the MeshBuilder class instead.
  21511. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21512. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21513. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21514. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21515. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21516. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21517. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21518. */
  21519. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  21520. var options = {
  21521. radius: radius,
  21522. tube: tube,
  21523. radialSegments: radialSegments,
  21524. tubularSegments: tubularSegments,
  21525. p: p,
  21526. q: q,
  21527. sideOrientation: sideOrientation,
  21528. updatable: updatable
  21529. };
  21530. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  21531. };
  21532. /**
  21533. * Creates a line mesh.
  21534. * Please consider using the same method from the MeshBuilder class instead.
  21535. * 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.
  21536. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21537. * The parameter `points` is an array successive Vector3.
  21538. * 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
  21539. * When updating an instance, remember that only point positions can change, not the number of points.
  21540. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21541. */
  21542. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  21543. var options = {
  21544. points: points,
  21545. updatable: updatable,
  21546. instance: instance
  21547. };
  21548. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  21549. };
  21550. /**
  21551. * Creates a dashed line mesh.
  21552. * Please consider using the same method from the MeshBuilder class instead.
  21553. * 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.
  21554. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21555. * The parameter `points` is an array successive Vector3.
  21556. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21557. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21558. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21559. * 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
  21560. * When updating an instance, remember that only point positions can change, not the number of points.
  21561. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21562. */
  21563. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  21564. var options = {
  21565. points: points,
  21566. dashSize: dashSize,
  21567. gapSize: gapSize,
  21568. dashNb: dashNb,
  21569. updatable: updatable,
  21570. instance: instance
  21571. };
  21572. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  21573. };
  21574. /**
  21575. * Creates a polygon mesh.
  21576. * Please consider using the same method from the MeshBuilder class instead.
  21577. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  21578. * 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.
  21579. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21580. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21581. * Remember you can only change the shape positions, not their number when updating a polygon.
  21582. */
  21583. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  21584. var options = {
  21585. shape: shape,
  21586. holes: holes,
  21587. updatable: updatable,
  21588. sideOrientation: sideOrientation
  21589. };
  21590. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  21591. };
  21592. /**
  21593. * Creates an extruded polygon mesh, with depth in the Y direction.
  21594. * Please consider using the same method from the MeshBuilder class instead.
  21595. */
  21596. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  21597. var options = {
  21598. shape: shape,
  21599. holes: holes,
  21600. depth: depth,
  21601. updatable: updatable,
  21602. sideOrientation: sideOrientation
  21603. };
  21604. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  21605. };
  21606. /**
  21607. * Creates an extruded shape mesh.
  21608. * 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.
  21609. * Please consider using the same method from the MeshBuilder class instead.
  21610. *
  21611. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21612. * 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
  21613. * extruded along the Z axis.
  21614. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21615. * 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.
  21616. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21617. * 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
  21618. * 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
  21619. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21620. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21621. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21622. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21623. */
  21624. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  21625. var options = {
  21626. shape: shape,
  21627. path: path,
  21628. scale: scale,
  21629. rotation: rotation,
  21630. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21631. sideOrientation: sideOrientation,
  21632. instance: instance,
  21633. updatable: updatable
  21634. };
  21635. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  21636. };
  21637. /**
  21638. * Creates an custom extruded shape mesh.
  21639. * 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.
  21640. * Please consider using the same method from the MeshBuilder class instead.
  21641. *
  21642. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21643. * 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
  21644. * extruded along the Z axis.
  21645. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21646. * 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
  21647. * and the distance of this point from the begining of the path :
  21648. * ```javascript
  21649. * var rotationFunction = function(i, distance) {
  21650. * // do things
  21651. * return rotationValue; }
  21652. * ```
  21653. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21654. * 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
  21655. * and the distance of this point from the begining of the path :
  21656. * ```javascript
  21657. * var scaleFunction = function(i, distance) {
  21658. * // do things
  21659. * return scaleValue;}
  21660. * ```
  21661. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21662. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21663. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21664. * 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
  21665. * 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
  21666. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21667. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21668. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21669. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21670. */
  21671. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  21672. var options = {
  21673. shape: shape,
  21674. path: path,
  21675. scaleFunction: scaleFunction,
  21676. rotationFunction: rotationFunction,
  21677. ribbonCloseArray: ribbonCloseArray,
  21678. ribbonClosePath: ribbonClosePath,
  21679. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21680. sideOrientation: sideOrientation,
  21681. instance: instance,
  21682. updatable: updatable
  21683. };
  21684. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  21685. };
  21686. /**
  21687. * Creates lathe mesh.
  21688. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  21689. * Please consider using the same method from the MeshBuilder class instead.
  21690. * 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
  21691. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  21692. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  21693. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  21694. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21695. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21696. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21697. */
  21698. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  21699. var options = {
  21700. shape: shape,
  21701. radius: radius,
  21702. tessellation: tessellation,
  21703. sideOrientation: sideOrientation,
  21704. updatable: updatable
  21705. };
  21706. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  21707. };
  21708. /**
  21709. * Creates a plane mesh.
  21710. * Please consider using the same method from the MeshBuilder class instead.
  21711. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  21712. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21713. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21714. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21715. */
  21716. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  21717. var options = {
  21718. size: size,
  21719. width: size,
  21720. height: size,
  21721. sideOrientation: sideOrientation,
  21722. updatable: updatable
  21723. };
  21724. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  21725. };
  21726. /**
  21727. * Creates a ground mesh.
  21728. * Please consider using the same method from the MeshBuilder class instead.
  21729. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  21730. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  21731. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21732. */
  21733. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  21734. var options = {
  21735. width: width,
  21736. height: height,
  21737. subdivisions: subdivisions,
  21738. updatable: updatable
  21739. };
  21740. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  21741. };
  21742. /**
  21743. * Creates a tiled ground mesh.
  21744. * Please consider using the same method from the MeshBuilder class instead.
  21745. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  21746. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  21747. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  21748. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  21749. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  21750. * numbers of subdivisions on the ground width and height of each tile.
  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. */
  21753. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  21754. var options = {
  21755. xmin: xmin,
  21756. zmin: zmin,
  21757. xmax: xmax,
  21758. zmax: zmax,
  21759. subdivisions: subdivisions,
  21760. precision: precision,
  21761. updatable: updatable
  21762. };
  21763. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  21764. };
  21765. /**
  21766. * Creates a ground mesh from a height map.
  21767. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  21768. * Please consider using the same method from the MeshBuilder class instead.
  21769. * The parameter `url` sets the URL of the height map image resource.
  21770. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  21771. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  21772. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  21773. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  21774. * 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).
  21775. * This function is passed the newly built mesh :
  21776. * ```javascript
  21777. * function(mesh) { // do things
  21778. * return; }
  21779. * ```
  21780. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21781. */
  21782. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  21783. var options = {
  21784. width: width,
  21785. height: height,
  21786. subdivisions: subdivisions,
  21787. minHeight: minHeight,
  21788. maxHeight: maxHeight,
  21789. updatable: updatable,
  21790. onReady: onReady
  21791. };
  21792. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  21793. };
  21794. /**
  21795. * Creates a tube mesh.
  21796. * 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.
  21797. * Please consider using the same method from the MeshBuilder class instead.
  21798. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21799. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21800. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21801. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21802. * 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.
  21803. * It must return a radius value (positive float) :
  21804. * ```javascript
  21805. * var radiusFunction = function(i, distance) {
  21806. * // do things
  21807. * return radius; }
  21808. * ```
  21809. * 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
  21810. * 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
  21811. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21812. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21813. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21814. */
  21815. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  21816. var options = {
  21817. path: path,
  21818. radius: radius,
  21819. tessellation: tessellation,
  21820. radiusFunction: radiusFunction,
  21821. arc: 1,
  21822. cap: cap,
  21823. updatable: updatable,
  21824. sideOrientation: sideOrientation,
  21825. instance: instance
  21826. };
  21827. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  21828. };
  21829. /**
  21830. * Creates a polyhedron mesh.
  21831. * Please consider using the same method from the MeshBuilder class instead.
  21832. * 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
  21833. * to choose the wanted type.
  21834. * The parameter `size` (positive float, default 1) sets the polygon size.
  21835. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  21836. * 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`.
  21837. * 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
  21838. * 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)`).
  21839. * 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
  21840. * 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.
  21841. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21842. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21843. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21844. */
  21845. Mesh.CreatePolyhedron = function (name, options, scene) {
  21846. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  21847. };
  21848. /**
  21849. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  21850. * Please consider using the same method from the MeshBuilder class instead.
  21851. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  21852. * 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`).
  21853. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  21854. * 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.
  21855. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21856. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21857. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21858. */
  21859. Mesh.CreateIcoSphere = function (name, options, scene) {
  21860. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  21861. };
  21862. /**
  21863. * Creates a decal mesh.
  21864. * Please consider using the same method from the MeshBuilder class instead.
  21865. * 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.
  21866. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  21867. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  21868. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  21869. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  21870. */
  21871. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  21872. var options = {
  21873. position: position,
  21874. normal: normal,
  21875. size: size,
  21876. angle: angle
  21877. };
  21878. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  21879. };
  21880. // Skeletons
  21881. /**
  21882. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21883. */
  21884. Mesh.prototype.setPositionsForCPUSkinning = function () {
  21885. var source;
  21886. if (!this._sourcePositions) {
  21887. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21888. this._sourcePositions = new Float32Array(source);
  21889. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  21890. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  21891. }
  21892. }
  21893. return this._sourcePositions;
  21894. };
  21895. /**
  21896. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21897. */
  21898. Mesh.prototype.setNormalsForCPUSkinning = function () {
  21899. var source;
  21900. if (!this._sourceNormals) {
  21901. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21902. this._sourceNormals = new Float32Array(source);
  21903. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  21904. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  21905. }
  21906. }
  21907. return this._sourceNormals;
  21908. };
  21909. /**
  21910. * Updates the vertex buffer by applying transformation from the bones.
  21911. * Returns the Mesh.
  21912. *
  21913. * @param {skeleton} skeleton to apply
  21914. */
  21915. Mesh.prototype.applySkeleton = function (skeleton) {
  21916. if (!this.geometry) {
  21917. return this;
  21918. }
  21919. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  21920. return this;
  21921. }
  21922. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  21923. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21924. return this;
  21925. }
  21926. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21927. return this;
  21928. }
  21929. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21930. return this;
  21931. }
  21932. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21933. return this;
  21934. }
  21935. if (!this._sourcePositions) {
  21936. var submeshes = this.subMeshes.slice();
  21937. this.setPositionsForCPUSkinning();
  21938. this.subMeshes = submeshes;
  21939. }
  21940. if (!this._sourceNormals) {
  21941. this.setNormalsForCPUSkinning();
  21942. }
  21943. // positionsData checks for not being Float32Array will only pass at most once
  21944. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21945. if (!(positionsData instanceof Float32Array)) {
  21946. positionsData = new Float32Array(positionsData);
  21947. }
  21948. // normalsData checks for not being Float32Array will only pass at most once
  21949. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21950. if (!(normalsData instanceof Float32Array)) {
  21951. normalsData = new Float32Array(normalsData);
  21952. }
  21953. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21954. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21955. var needExtras = this.numBoneInfluencers > 4;
  21956. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  21957. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  21958. var skeletonMatrices = skeleton.getTransformMatrices(this);
  21959. var tempVector3 = BABYLON.Vector3.Zero();
  21960. var finalMatrix = new BABYLON.Matrix();
  21961. var tempMatrix = new BABYLON.Matrix();
  21962. var matWeightIdx = 0;
  21963. var inf;
  21964. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  21965. var weight;
  21966. for (inf = 0; inf < 4; inf++) {
  21967. weight = matricesWeightsData[matWeightIdx + inf];
  21968. if (weight > 0) {
  21969. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21970. finalMatrix.addToSelf(tempMatrix);
  21971. }
  21972. else
  21973. break;
  21974. }
  21975. if (needExtras) {
  21976. for (inf = 0; inf < 4; inf++) {
  21977. weight = matricesWeightsExtraData[matWeightIdx + inf];
  21978. if (weight > 0) {
  21979. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21980. finalMatrix.addToSelf(tempMatrix);
  21981. }
  21982. else
  21983. break;
  21984. }
  21985. }
  21986. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  21987. tempVector3.toArray(positionsData, index);
  21988. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  21989. tempVector3.toArray(normalsData, index);
  21990. finalMatrix.reset();
  21991. }
  21992. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  21993. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  21994. return this;
  21995. };
  21996. // Tools
  21997. /**
  21998. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  21999. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  22000. */
  22001. Mesh.MinMax = function (meshes) {
  22002. var minVector = null;
  22003. var maxVector = null;
  22004. meshes.forEach(function (mesh, index, array) {
  22005. var boundingBox = mesh.getBoundingInfo().boundingBox;
  22006. if (!minVector) {
  22007. minVector = boundingBox.minimumWorld;
  22008. maxVector = boundingBox.maximumWorld;
  22009. }
  22010. else {
  22011. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  22012. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  22013. }
  22014. });
  22015. return {
  22016. min: minVector,
  22017. max: maxVector
  22018. };
  22019. };
  22020. /**
  22021. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  22022. */
  22023. Mesh.Center = function (meshesOrMinMaxVector) {
  22024. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  22025. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  22026. };
  22027. /**
  22028. * Merge the array of meshes into a single mesh for performance reasons.
  22029. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  22030. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  22031. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  22032. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  22033. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  22034. */
  22035. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  22036. if (disposeSource === void 0) { disposeSource = true; }
  22037. var index;
  22038. if (!allow32BitsIndices) {
  22039. var totalVertices = 0;
  22040. // Counting vertices
  22041. for (index = 0; index < meshes.length; index++) {
  22042. if (meshes[index]) {
  22043. totalVertices += meshes[index].getTotalVertices();
  22044. if (totalVertices > 65536) {
  22045. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  22046. return null;
  22047. }
  22048. }
  22049. }
  22050. }
  22051. // Merge
  22052. var vertexData;
  22053. var otherVertexData;
  22054. var indiceArray = new Array();
  22055. var source;
  22056. for (index = 0; index < meshes.length; index++) {
  22057. if (meshes[index]) {
  22058. meshes[index].computeWorldMatrix(true);
  22059. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  22060. otherVertexData.transform(meshes[index].getWorldMatrix());
  22061. if (vertexData) {
  22062. vertexData.merge(otherVertexData);
  22063. }
  22064. else {
  22065. vertexData = otherVertexData;
  22066. source = meshes[index];
  22067. }
  22068. if (subdivideWithSubMeshes) {
  22069. indiceArray.push(meshes[index].getTotalIndices());
  22070. }
  22071. }
  22072. }
  22073. if (!meshSubclass) {
  22074. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  22075. }
  22076. vertexData.applyToMesh(meshSubclass);
  22077. // Setting properties
  22078. meshSubclass.material = source.material;
  22079. meshSubclass.checkCollisions = source.checkCollisions;
  22080. // Cleaning
  22081. if (disposeSource) {
  22082. for (index = 0; index < meshes.length; index++) {
  22083. if (meshes[index]) {
  22084. meshes[index].dispose();
  22085. }
  22086. }
  22087. }
  22088. // Subdivide
  22089. if (subdivideWithSubMeshes) {
  22090. //-- Suppresions du submesh global
  22091. meshSubclass.releaseSubMeshes();
  22092. index = 0;
  22093. var offset = 0;
  22094. //-- aplique la subdivision en fonction du tableau d'indices
  22095. while (index < indiceArray.length) {
  22096. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  22097. offset += indiceArray[index];
  22098. index++;
  22099. }
  22100. }
  22101. return meshSubclass;
  22102. };
  22103. return Mesh;
  22104. }(BABYLON.AbstractMesh));
  22105. // Consts
  22106. Mesh._FRONTSIDE = 0;
  22107. Mesh._BACKSIDE = 1;
  22108. Mesh._DOUBLESIDE = 2;
  22109. Mesh._DEFAULTSIDE = 0;
  22110. Mesh._NO_CAP = 0;
  22111. Mesh._CAP_START = 1;
  22112. Mesh._CAP_END = 2;
  22113. Mesh._CAP_ALL = 3;
  22114. BABYLON.Mesh = Mesh;
  22115. })(BABYLON || (BABYLON = {}));
  22116. //# sourceMappingURL=babylon.mesh.js.map
  22117. var BABYLON;
  22118. (function (BABYLON) {
  22119. var SubMesh = (function () {
  22120. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  22121. if (createBoundingBox === void 0) { createBoundingBox = true; }
  22122. this.materialIndex = materialIndex;
  22123. this.verticesStart = verticesStart;
  22124. this.verticesCount = verticesCount;
  22125. this.indexStart = indexStart;
  22126. this.indexCount = indexCount;
  22127. this._renderId = 0;
  22128. this._mesh = mesh;
  22129. this._renderingMesh = renderingMesh || mesh;
  22130. mesh.subMeshes.push(this);
  22131. this._trianglePlanes = [];
  22132. this._id = mesh.subMeshes.length - 1;
  22133. if (createBoundingBox) {
  22134. this.refreshBoundingInfo();
  22135. mesh.computeWorldMatrix(true);
  22136. }
  22137. }
  22138. Object.defineProperty(SubMesh.prototype, "effect", {
  22139. get: function () {
  22140. return this._materialEffect;
  22141. },
  22142. enumerable: true,
  22143. configurable: true
  22144. });
  22145. SubMesh.prototype.setEffect = function (effect, defines) {
  22146. if (this._materialEffect === effect) {
  22147. return;
  22148. }
  22149. this._materialDefines = defines;
  22150. this._materialEffect = effect;
  22151. };
  22152. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  22153. get: function () {
  22154. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  22155. },
  22156. enumerable: true,
  22157. configurable: true
  22158. });
  22159. /**
  22160. * Returns the submesh BoudingInfo object.
  22161. */
  22162. SubMesh.prototype.getBoundingInfo = function () {
  22163. if (this.IsGlobal) {
  22164. return this._mesh.getBoundingInfo();
  22165. }
  22166. return this._boundingInfo;
  22167. };
  22168. /**
  22169. * Sets the submesh BoundingInfo.
  22170. * Return the SubMesh.
  22171. */
  22172. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  22173. this._boundingInfo = boundingInfo;
  22174. return this;
  22175. };
  22176. /**
  22177. * Returns the mesh of the current submesh.
  22178. */
  22179. SubMesh.prototype.getMesh = function () {
  22180. return this._mesh;
  22181. };
  22182. /**
  22183. * Returns the rendering mesh of the submesh.
  22184. */
  22185. SubMesh.prototype.getRenderingMesh = function () {
  22186. return this._renderingMesh;
  22187. };
  22188. /**
  22189. * Returns the submesh material.
  22190. */
  22191. SubMesh.prototype.getMaterial = function () {
  22192. var rootMaterial = this._renderingMesh.material;
  22193. if (rootMaterial && rootMaterial.getSubMaterial) {
  22194. var multiMaterial = rootMaterial;
  22195. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  22196. if (this._currentMaterial !== effectiveMaterial) {
  22197. this._currentMaterial = effectiveMaterial;
  22198. if (this._materialDefines) {
  22199. this._materialDefines.markAllAsDirty();
  22200. }
  22201. }
  22202. return effectiveMaterial;
  22203. }
  22204. if (!rootMaterial) {
  22205. return this._mesh.getScene().defaultMaterial;
  22206. }
  22207. return rootMaterial;
  22208. };
  22209. // Methods
  22210. /**
  22211. * Sets a new updated BoundingInfo object to the submesh.
  22212. * Returns the SubMesh.
  22213. */
  22214. SubMesh.prototype.refreshBoundingInfo = function () {
  22215. this._lastColliderWorldVertices = null;
  22216. if (this.IsGlobal) {
  22217. return;
  22218. }
  22219. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22220. if (!data) {
  22221. this._boundingInfo = this._mesh._boundingInfo;
  22222. return;
  22223. }
  22224. var indices = this._renderingMesh.getIndices();
  22225. var extend;
  22226. //is this the only submesh?
  22227. if (this.indexStart === 0 && this.indexCount === indices.length) {
  22228. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  22229. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  22230. }
  22231. else {
  22232. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  22233. }
  22234. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22235. return this;
  22236. };
  22237. SubMesh.prototype._checkCollision = function (collider) {
  22238. return this.getBoundingInfo()._checkCollision(collider);
  22239. };
  22240. /**
  22241. * Updates the submesh BoundingInfo.
  22242. * Returns the Submesh.
  22243. */
  22244. SubMesh.prototype.updateBoundingInfo = function (world) {
  22245. if (!this.getBoundingInfo()) {
  22246. this.refreshBoundingInfo();
  22247. }
  22248. this.getBoundingInfo().update(world);
  22249. return this;
  22250. };
  22251. /**
  22252. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  22253. * Boolean returned.
  22254. */
  22255. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  22256. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  22257. };
  22258. /**
  22259. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  22260. * Boolean returned.
  22261. */
  22262. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  22263. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  22264. };
  22265. /**
  22266. * Renders the submesh.
  22267. * Returns it.
  22268. */
  22269. SubMesh.prototype.render = function (enableAlphaMode) {
  22270. this._renderingMesh.render(this, enableAlphaMode);
  22271. return this;
  22272. };
  22273. /**
  22274. * Returns a new Index Buffer.
  22275. * Type returned : WebGLBuffer.
  22276. */
  22277. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  22278. if (!this._linesIndexBuffer) {
  22279. var linesIndices = [];
  22280. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22281. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  22282. }
  22283. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  22284. this.linesIndexCount = linesIndices.length;
  22285. }
  22286. return this._linesIndexBuffer;
  22287. };
  22288. /**
  22289. * True is the passed Ray intersects the submesh bounding box.
  22290. * Boolean returned.
  22291. */
  22292. SubMesh.prototype.canIntersects = function (ray) {
  22293. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  22294. };
  22295. /**
  22296. * Returns an object IntersectionInfo.
  22297. */
  22298. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  22299. var intersectInfo = null;
  22300. // LineMesh first as it's also a Mesh...
  22301. if (this._mesh instanceof BABYLON.LinesMesh) {
  22302. var lineMesh = this._mesh;
  22303. // Line test
  22304. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  22305. var p0 = positions[indices[index]];
  22306. var p1 = positions[indices[index + 1]];
  22307. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  22308. if (length < 0) {
  22309. continue;
  22310. }
  22311. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  22312. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  22313. if (fastCheck) {
  22314. break;
  22315. }
  22316. }
  22317. }
  22318. }
  22319. else {
  22320. // Triangles test
  22321. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22322. var p0 = positions[indices[index]];
  22323. var p1 = positions[indices[index + 1]];
  22324. var p2 = positions[indices[index + 2]];
  22325. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  22326. if (currentIntersectInfo) {
  22327. if (currentIntersectInfo.distance < 0) {
  22328. continue;
  22329. }
  22330. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  22331. intersectInfo = currentIntersectInfo;
  22332. intersectInfo.faceId = index / 3;
  22333. if (fastCheck) {
  22334. break;
  22335. }
  22336. }
  22337. }
  22338. }
  22339. }
  22340. return intersectInfo;
  22341. };
  22342. // Clone
  22343. /**
  22344. * Creates a new Submesh from the passed Mesh.
  22345. */
  22346. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  22347. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  22348. if (!this.IsGlobal) {
  22349. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  22350. }
  22351. return result;
  22352. };
  22353. // Dispose
  22354. /**
  22355. * Disposes the Submesh.
  22356. * Returns nothing.
  22357. */
  22358. SubMesh.prototype.dispose = function () {
  22359. if (this._linesIndexBuffer) {
  22360. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  22361. this._linesIndexBuffer = null;
  22362. }
  22363. // Remove from mesh
  22364. var index = this._mesh.subMeshes.indexOf(this);
  22365. this._mesh.subMeshes.splice(index, 1);
  22366. };
  22367. // Statics
  22368. /**
  22369. * Creates a new Submesh from the passed parameters :
  22370. * - materialIndex (integer) : the index of the main mesh material.
  22371. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  22372. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  22373. * - mesh (Mesh) : the main mesh to create the submesh from.
  22374. * - renderingMesh (optional Mesh) : rendering mesh.
  22375. */
  22376. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  22377. var minVertexIndex = Number.MAX_VALUE;
  22378. var maxVertexIndex = -Number.MAX_VALUE;
  22379. renderingMesh = renderingMesh || mesh;
  22380. var indices = renderingMesh.getIndices();
  22381. for (var index = startIndex; index < startIndex + indexCount; index++) {
  22382. var vertexIndex = indices[index];
  22383. if (vertexIndex < minVertexIndex)
  22384. minVertexIndex = vertexIndex;
  22385. if (vertexIndex > maxVertexIndex)
  22386. maxVertexIndex = vertexIndex;
  22387. }
  22388. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  22389. };
  22390. return SubMesh;
  22391. }());
  22392. BABYLON.SubMesh = SubMesh;
  22393. })(BABYLON || (BABYLON = {}));
  22394. //# sourceMappingURL=babylon.subMesh.js.map
  22395. var BABYLON;
  22396. (function (BABYLON) {
  22397. var EffectFallbacks = (function () {
  22398. function EffectFallbacks() {
  22399. this._defines = {};
  22400. this._currentRank = 32;
  22401. this._maxRank = -1;
  22402. }
  22403. EffectFallbacks.prototype.addFallback = function (rank, define) {
  22404. if (!this._defines[rank]) {
  22405. if (rank < this._currentRank) {
  22406. this._currentRank = rank;
  22407. }
  22408. if (rank > this._maxRank) {
  22409. this._maxRank = rank;
  22410. }
  22411. this._defines[rank] = new Array();
  22412. }
  22413. this._defines[rank].push(define);
  22414. };
  22415. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  22416. this._meshRank = rank;
  22417. this._mesh = mesh;
  22418. if (rank < this._currentRank) {
  22419. this._currentRank = rank;
  22420. }
  22421. if (rank > this._maxRank) {
  22422. this._maxRank = rank;
  22423. }
  22424. };
  22425. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  22426. get: function () {
  22427. return this._currentRank <= this._maxRank;
  22428. },
  22429. enumerable: true,
  22430. configurable: true
  22431. });
  22432. EffectFallbacks.prototype.reduce = function (currentDefines) {
  22433. // First we try to switch to CPU skinning
  22434. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  22435. this._mesh.computeBonesUsingShaders = false;
  22436. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  22437. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  22438. var scene = this._mesh.getScene();
  22439. for (var index = 0; index < scene.meshes.length; index++) {
  22440. var otherMesh = scene.meshes[index];
  22441. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  22442. otherMesh.computeBonesUsingShaders = false;
  22443. }
  22444. }
  22445. }
  22446. else {
  22447. var currentFallbacks = this._defines[this._currentRank];
  22448. if (currentFallbacks) {
  22449. for (var index = 0; index < currentFallbacks.length; index++) {
  22450. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  22451. }
  22452. }
  22453. this._currentRank++;
  22454. }
  22455. return currentDefines;
  22456. };
  22457. return EffectFallbacks;
  22458. }());
  22459. BABYLON.EffectFallbacks = EffectFallbacks;
  22460. var EffectCreationOptions = (function () {
  22461. function EffectCreationOptions() {
  22462. }
  22463. return EffectCreationOptions;
  22464. }());
  22465. BABYLON.EffectCreationOptions = EffectCreationOptions;
  22466. var Effect = (function () {
  22467. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  22468. var _this = this;
  22469. this.uniqueId = 0;
  22470. this._uniformBuffersNames = {};
  22471. this._isReady = false;
  22472. this._compilationError = "";
  22473. this._valueCache = {};
  22474. this.name = baseName;
  22475. if (attributesNamesOrOptions.attributes) {
  22476. var options = attributesNamesOrOptions;
  22477. this._engine = uniformsNamesOrEngine;
  22478. this._attributesNames = options.attributes;
  22479. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  22480. this._samplers = options.samplers;
  22481. this.defines = options.defines;
  22482. this.onError = options.onError;
  22483. this.onCompiled = options.onCompiled;
  22484. this._fallbacks = options.fallbacks;
  22485. this._indexParameters = options.indexParameters;
  22486. if (options.uniformBuffersNames) {
  22487. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  22488. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  22489. }
  22490. }
  22491. }
  22492. else {
  22493. this._engine = engine;
  22494. this.defines = defines;
  22495. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  22496. this._samplers = samplers;
  22497. this._attributesNames = attributesNamesOrOptions;
  22498. this.onError = onError;
  22499. this.onCompiled = onCompiled;
  22500. this._indexParameters = indexParameters;
  22501. this._fallbacks = fallbacks;
  22502. }
  22503. this.uniqueId = Effect._uniqueIdSeed++;
  22504. var vertexSource;
  22505. var fragmentSource;
  22506. if (baseName.vertexElement) {
  22507. vertexSource = document.getElementById(baseName.vertexElement);
  22508. if (!vertexSource) {
  22509. vertexSource = baseName.vertexElement;
  22510. }
  22511. }
  22512. else {
  22513. vertexSource = baseName.vertex || baseName;
  22514. }
  22515. if (baseName.fragmentElement) {
  22516. fragmentSource = document.getElementById(baseName.fragmentElement);
  22517. if (!fragmentSource) {
  22518. fragmentSource = baseName.fragmentElement;
  22519. }
  22520. }
  22521. else {
  22522. fragmentSource = baseName.fragment || baseName;
  22523. }
  22524. this._loadVertexShader(vertexSource, function (vertexCode) {
  22525. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  22526. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  22527. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  22528. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  22529. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  22530. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, _this._attributesNames, _this.defines, _this._fallbacks);
  22531. });
  22532. });
  22533. });
  22534. });
  22535. });
  22536. });
  22537. }
  22538. Object.defineProperty(Effect.prototype, "key", {
  22539. get: function () {
  22540. return this._key;
  22541. },
  22542. enumerable: true,
  22543. configurable: true
  22544. });
  22545. // Properties
  22546. Effect.prototype.isReady = function () {
  22547. return this._isReady;
  22548. };
  22549. Effect.prototype.getProgram = function () {
  22550. return this._program;
  22551. };
  22552. Effect.prototype.getAttributesNames = function () {
  22553. return this._attributesNames;
  22554. };
  22555. Effect.prototype.getAttributeLocation = function (index) {
  22556. return this._attributes[index];
  22557. };
  22558. Effect.prototype.getAttributeLocationByName = function (name) {
  22559. var index = this._attributesNames.indexOf(name);
  22560. return this._attributes[index];
  22561. };
  22562. Effect.prototype.getAttributesCount = function () {
  22563. return this._attributes.length;
  22564. };
  22565. Effect.prototype.getUniformIndex = function (uniformName) {
  22566. return this._uniformsNames.indexOf(uniformName);
  22567. };
  22568. Effect.prototype.getUniform = function (uniformName) {
  22569. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  22570. };
  22571. Effect.prototype.getSamplers = function () {
  22572. return this._samplers;
  22573. };
  22574. Effect.prototype.getCompilationError = function () {
  22575. return this._compilationError;
  22576. };
  22577. Effect.prototype.getVertexShaderSource = function () {
  22578. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  22579. };
  22580. Effect.prototype.getFragmentShaderSource = function () {
  22581. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  22582. };
  22583. // Methods
  22584. Effect.prototype._loadVertexShader = function (vertex, callback) {
  22585. // DOM element ?
  22586. if (vertex instanceof HTMLElement) {
  22587. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  22588. callback(vertexCode);
  22589. return;
  22590. }
  22591. // Base64 encoded ?
  22592. if (vertex.substr(0, 7) === "base64:") {
  22593. var vertexBinary = window.atob(vertex.substr(7));
  22594. callback(vertexBinary);
  22595. return;
  22596. }
  22597. // Is in local store ?
  22598. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  22599. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  22600. return;
  22601. }
  22602. var vertexShaderUrl;
  22603. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  22604. vertexShaderUrl = vertex;
  22605. }
  22606. else {
  22607. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  22608. }
  22609. // Vertex shader
  22610. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  22611. };
  22612. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  22613. // DOM element ?
  22614. if (fragment instanceof HTMLElement) {
  22615. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  22616. callback(fragmentCode);
  22617. return;
  22618. }
  22619. // Base64 encoded ?
  22620. if (fragment.substr(0, 7) === "base64:") {
  22621. var fragmentBinary = window.atob(fragment.substr(7));
  22622. callback(fragmentBinary);
  22623. return;
  22624. }
  22625. // Is in local store ?
  22626. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  22627. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  22628. return;
  22629. }
  22630. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  22631. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  22632. return;
  22633. }
  22634. var fragmentShaderUrl;
  22635. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  22636. fragmentShaderUrl = fragment;
  22637. }
  22638. else {
  22639. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  22640. }
  22641. // Fragment shader
  22642. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  22643. };
  22644. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  22645. // Rebuild shaders source code
  22646. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  22647. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  22648. vertexCode = prefix + vertexCode;
  22649. fragmentCode = prefix + fragmentCode;
  22650. // Number lines of shaders source code
  22651. var i = 2;
  22652. var regex = /\n/gm;
  22653. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  22654. i = 2;
  22655. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  22656. // Dump shaders name and formatted source code
  22657. if (this.name.vertexElement) {
  22658. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  22659. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  22660. }
  22661. else if (this.name.vertex) {
  22662. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  22663. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  22664. }
  22665. else {
  22666. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  22667. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  22668. }
  22669. };
  22670. ;
  22671. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  22672. var preparedSourceCode = this._processPrecision(sourceCode);
  22673. if (this._engine.webGLVersion == 1) {
  22674. callback(preparedSourceCode);
  22675. return;
  22676. }
  22677. // Already converted
  22678. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  22679. callback(preparedSourceCode.replace("#version 300 es", ""));
  22680. return;
  22681. }
  22682. // Remove extensions
  22683. // #extension GL_OES_standard_derivatives : enable
  22684. // #extension GL_EXT_shader_texture_lod : enable
  22685. // #extension GL_EXT_frag_depth : enable
  22686. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  22687. var result = preparedSourceCode.replace(regex, "");
  22688. // Migrate to GLSL v300
  22689. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  22690. result = result.replace(/attribute[ \t]/g, "in ");
  22691. result = result.replace(/[ \t]attribute/g, " in");
  22692. if (isFragment) {
  22693. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  22694. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  22695. result = result.replace(/texture2D\(/g, "texture(");
  22696. result = result.replace(/textureCube\(/g, "texture(");
  22697. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  22698. result = result.replace(/gl_FragColor/g, "glFragColor");
  22699. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  22700. }
  22701. callback(result);
  22702. };
  22703. Effect.prototype._processIncludes = function (sourceCode, callback) {
  22704. var _this = this;
  22705. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  22706. var match = regex.exec(sourceCode);
  22707. var returnValue = new String(sourceCode);
  22708. while (match != null) {
  22709. var includeFile = match[1];
  22710. // Uniform declaration
  22711. if (includeFile.indexOf("__decl__") !== -1) {
  22712. includeFile = includeFile.replace(/__decl__/, "");
  22713. if (this._engine.webGLVersion != 1) {
  22714. includeFile = includeFile.replace(/Vertex/, "Ubo");
  22715. includeFile = includeFile.replace(/Fragment/, "Ubo");
  22716. }
  22717. includeFile = includeFile + "Declaration";
  22718. }
  22719. if (Effect.IncludesShadersStore[includeFile]) {
  22720. // Substitution
  22721. var includeContent = Effect.IncludesShadersStore[includeFile];
  22722. if (match[2]) {
  22723. var splits = match[3].split(",");
  22724. for (var index = 0; index < splits.length; index += 2) {
  22725. var source = new RegExp(splits[index], "g");
  22726. var dest = splits[index + 1];
  22727. includeContent = includeContent.replace(source, dest);
  22728. }
  22729. }
  22730. if (match[4]) {
  22731. var indexString = match[5];
  22732. if (indexString.indexOf("..") !== -1) {
  22733. var indexSplits = indexString.split("..");
  22734. var minIndex = parseInt(indexSplits[0]);
  22735. var maxIndex = parseInt(indexSplits[1]);
  22736. var sourceIncludeContent = includeContent.slice(0);
  22737. includeContent = "";
  22738. if (isNaN(maxIndex)) {
  22739. maxIndex = this._indexParameters[indexSplits[1]];
  22740. }
  22741. for (var i = minIndex; i < maxIndex; i++) {
  22742. if (this._engine.webGLVersion === 1) {
  22743. // Ubo replacement
  22744. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  22745. return p1 + "{X}";
  22746. });
  22747. }
  22748. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  22749. }
  22750. }
  22751. else {
  22752. if (this._engine.webGLVersion === 1) {
  22753. // Ubo replacement
  22754. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  22755. return p1 + "{X}";
  22756. });
  22757. }
  22758. includeContent = includeContent.replace(/\{X\}/g, indexString);
  22759. }
  22760. }
  22761. // Replace
  22762. returnValue = returnValue.replace(match[0], includeContent);
  22763. }
  22764. else {
  22765. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  22766. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  22767. Effect.IncludesShadersStore[includeFile] = fileContent;
  22768. _this._processIncludes(returnValue, callback);
  22769. });
  22770. return;
  22771. }
  22772. match = regex.exec(sourceCode);
  22773. }
  22774. callback(returnValue);
  22775. };
  22776. Effect.prototype._processPrecision = function (source) {
  22777. if (source.indexOf("precision highp float") === -1) {
  22778. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  22779. source = "precision mediump float;\n" + source;
  22780. }
  22781. else {
  22782. source = "precision highp float;\n" + source;
  22783. }
  22784. }
  22785. else {
  22786. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  22787. source = source.replace("precision highp float", "precision mediump float");
  22788. }
  22789. }
  22790. return source;
  22791. };
  22792. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  22793. try {
  22794. var engine = this._engine;
  22795. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  22796. if (engine.webGLVersion > 1) {
  22797. for (var name in this._uniformBuffersNames) {
  22798. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  22799. }
  22800. }
  22801. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  22802. this._attributes = engine.getAttributes(this._program, attributesNames);
  22803. var index;
  22804. for (index = 0; index < this._samplers.length; index++) {
  22805. var sampler = this.getUniform(this._samplers[index]);
  22806. if (sampler == null) {
  22807. this._samplers.splice(index, 1);
  22808. index--;
  22809. }
  22810. }
  22811. engine.bindSamplers(this);
  22812. this._compilationError = "";
  22813. this._isReady = true;
  22814. if (this.onCompiled) {
  22815. this.onCompiled(this);
  22816. }
  22817. }
  22818. catch (e) {
  22819. this._compilationError = e.message;
  22820. // Let's go through fallbacks then
  22821. BABYLON.Tools.Error("Unable to compile effect:");
  22822. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  22823. return " " + uniform;
  22824. }));
  22825. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  22826. return " " + attribute;
  22827. }));
  22828. this._dumpShadersSource(vertexSourceCode, fragmentSourceCode, defines);
  22829. BABYLON.Tools.Error("Error: " + this._compilationError);
  22830. if (fallbacks && fallbacks.isMoreFallbacks) {
  22831. BABYLON.Tools.Error("Trying next fallback.");
  22832. defines = fallbacks.reduce(defines);
  22833. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  22834. }
  22835. else {
  22836. if (this.onError) {
  22837. this.onError(this, this._compilationError);
  22838. }
  22839. }
  22840. }
  22841. };
  22842. Object.defineProperty(Effect.prototype, "isSupported", {
  22843. get: function () {
  22844. return this._compilationError === "";
  22845. },
  22846. enumerable: true,
  22847. configurable: true
  22848. });
  22849. Effect.prototype._bindTexture = function (channel, texture) {
  22850. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  22851. };
  22852. Effect.prototype.setTexture = function (channel, texture) {
  22853. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  22854. };
  22855. Effect.prototype.setTextureArray = function (channel, textures) {
  22856. if (this._samplers.indexOf(channel + "Ex") === -1) {
  22857. var initialPos = this._samplers.indexOf(channel);
  22858. for (var index = 1; index < textures.length; index++) {
  22859. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  22860. }
  22861. }
  22862. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  22863. };
  22864. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  22865. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  22866. };
  22867. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  22868. var cache = this._valueCache[uniformName];
  22869. var flag = matrix.updateFlag;
  22870. if (cache !== undefined && cache === flag) {
  22871. return false;
  22872. }
  22873. this._valueCache[uniformName] = flag;
  22874. return true;
  22875. };
  22876. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  22877. var cache = this._valueCache[uniformName];
  22878. if (!cache) {
  22879. cache = [x, y];
  22880. this._valueCache[uniformName] = cache;
  22881. return true;
  22882. }
  22883. var changed = false;
  22884. if (cache[0] !== x) {
  22885. cache[0] = x;
  22886. changed = true;
  22887. }
  22888. if (cache[1] !== y) {
  22889. cache[1] = y;
  22890. changed = true;
  22891. }
  22892. return changed;
  22893. };
  22894. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  22895. var cache = this._valueCache[uniformName];
  22896. if (!cache) {
  22897. cache = [x, y, z];
  22898. this._valueCache[uniformName] = cache;
  22899. return true;
  22900. }
  22901. var changed = false;
  22902. if (cache[0] !== x) {
  22903. cache[0] = x;
  22904. changed = true;
  22905. }
  22906. if (cache[1] !== y) {
  22907. cache[1] = y;
  22908. changed = true;
  22909. }
  22910. if (cache[2] !== z) {
  22911. cache[2] = z;
  22912. changed = true;
  22913. }
  22914. return changed;
  22915. };
  22916. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  22917. var cache = this._valueCache[uniformName];
  22918. if (!cache) {
  22919. cache = [x, y, z, w];
  22920. this._valueCache[uniformName] = cache;
  22921. return true;
  22922. }
  22923. var changed = false;
  22924. if (cache[0] !== x) {
  22925. cache[0] = x;
  22926. changed = true;
  22927. }
  22928. if (cache[1] !== y) {
  22929. cache[1] = y;
  22930. changed = true;
  22931. }
  22932. if (cache[2] !== z) {
  22933. cache[2] = z;
  22934. changed = true;
  22935. }
  22936. if (cache[3] !== w) {
  22937. cache[3] = w;
  22938. changed = true;
  22939. }
  22940. return changed;
  22941. };
  22942. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  22943. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  22944. return;
  22945. }
  22946. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  22947. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  22948. };
  22949. Effect.prototype.bindUniformBlock = function (blockName, index) {
  22950. this._engine.bindUniformBlock(this._program, blockName, index);
  22951. };
  22952. Effect.prototype.setIntArray = function (uniformName, array) {
  22953. this._valueCache[uniformName] = null;
  22954. this._engine.setIntArray(this.getUniform(uniformName), array);
  22955. return this;
  22956. };
  22957. Effect.prototype.setIntArray2 = function (uniformName, array) {
  22958. this._valueCache[uniformName] = null;
  22959. this._engine.setIntArray2(this.getUniform(uniformName), array);
  22960. return this;
  22961. };
  22962. Effect.prototype.setIntArray3 = function (uniformName, array) {
  22963. this._valueCache[uniformName] = null;
  22964. this._engine.setIntArray3(this.getUniform(uniformName), array);
  22965. return this;
  22966. };
  22967. Effect.prototype.setIntArray4 = function (uniformName, array) {
  22968. this._valueCache[uniformName] = null;
  22969. this._engine.setIntArray4(this.getUniform(uniformName), array);
  22970. return this;
  22971. };
  22972. Effect.prototype.setFloatArray = function (uniformName, array) {
  22973. this._valueCache[uniformName] = null;
  22974. this._engine.setFloatArray(this.getUniform(uniformName), array);
  22975. return this;
  22976. };
  22977. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  22978. this._valueCache[uniformName] = null;
  22979. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  22980. return this;
  22981. };
  22982. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  22983. this._valueCache[uniformName] = null;
  22984. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  22985. return this;
  22986. };
  22987. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  22988. this._valueCache[uniformName] = null;
  22989. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  22990. return this;
  22991. };
  22992. Effect.prototype.setArray = function (uniformName, array) {
  22993. this._valueCache[uniformName] = null;
  22994. this._engine.setArray(this.getUniform(uniformName), array);
  22995. return this;
  22996. };
  22997. Effect.prototype.setArray2 = function (uniformName, array) {
  22998. this._valueCache[uniformName] = null;
  22999. this._engine.setArray2(this.getUniform(uniformName), array);
  23000. return this;
  23001. };
  23002. Effect.prototype.setArray3 = function (uniformName, array) {
  23003. this._valueCache[uniformName] = null;
  23004. this._engine.setArray3(this.getUniform(uniformName), array);
  23005. return this;
  23006. };
  23007. Effect.prototype.setArray4 = function (uniformName, array) {
  23008. this._valueCache[uniformName] = null;
  23009. this._engine.setArray4(this.getUniform(uniformName), array);
  23010. return this;
  23011. };
  23012. Effect.prototype.setMatrices = function (uniformName, matrices) {
  23013. if (!matrices) {
  23014. return;
  23015. }
  23016. this._valueCache[uniformName] = null;
  23017. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  23018. return this;
  23019. };
  23020. Effect.prototype.setMatrix = function (uniformName, matrix) {
  23021. if (this._cacheMatrix(uniformName, matrix)) {
  23022. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  23023. }
  23024. return this;
  23025. };
  23026. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  23027. this._valueCache[uniformName] = null;
  23028. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  23029. return this;
  23030. };
  23031. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  23032. this._valueCache[uniformName] = null;
  23033. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  23034. return this;
  23035. };
  23036. Effect.prototype.setFloat = function (uniformName, value) {
  23037. var cache = this._valueCache[uniformName];
  23038. if (cache !== undefined && cache === value)
  23039. return this;
  23040. this._valueCache[uniformName] = value;
  23041. this._engine.setFloat(this.getUniform(uniformName), value);
  23042. return this;
  23043. };
  23044. Effect.prototype.setBool = function (uniformName, bool) {
  23045. var cache = this._valueCache[uniformName];
  23046. if (cache !== undefined && cache === bool)
  23047. return this;
  23048. this._valueCache[uniformName] = bool;
  23049. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  23050. return this;
  23051. };
  23052. Effect.prototype.setVector2 = function (uniformName, vector2) {
  23053. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  23054. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  23055. }
  23056. return this;
  23057. };
  23058. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  23059. if (this._cacheFloat2(uniformName, x, y)) {
  23060. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  23061. }
  23062. return this;
  23063. };
  23064. Effect.prototype.setVector3 = function (uniformName, vector3) {
  23065. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  23066. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  23067. }
  23068. return this;
  23069. };
  23070. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  23071. if (this._cacheFloat3(uniformName, x, y, z)) {
  23072. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  23073. }
  23074. return this;
  23075. };
  23076. Effect.prototype.setVector4 = function (uniformName, vector4) {
  23077. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  23078. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  23079. }
  23080. return this;
  23081. };
  23082. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  23083. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  23084. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  23085. }
  23086. return this;
  23087. };
  23088. Effect.prototype.setColor3 = function (uniformName, color3) {
  23089. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  23090. this._engine.setColor3(this.getUniform(uniformName), color3);
  23091. }
  23092. return this;
  23093. };
  23094. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  23095. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  23096. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  23097. }
  23098. return this;
  23099. };
  23100. Effect.prototype._recombineShader = function (node) {
  23101. if (node.define) {
  23102. if (node.condition) {
  23103. var defineIndex = this.defines.indexOf("#define " + node.define);
  23104. if (defineIndex === -1) {
  23105. return null;
  23106. }
  23107. var nextComma = this.defines.indexOf("\n", defineIndex);
  23108. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  23109. var condition = defineValue + node.condition;
  23110. if (!eval(condition)) {
  23111. return null;
  23112. }
  23113. }
  23114. else if (node.ndef) {
  23115. if (this.defines.indexOf("#define " + node.define) !== -1) {
  23116. return null;
  23117. }
  23118. }
  23119. else if (this.defines.indexOf("#define " + node.define) === -1) {
  23120. return null;
  23121. }
  23122. }
  23123. var result = "";
  23124. for (var index = 0; index < node.children.length; index++) {
  23125. var line = node.children[index];
  23126. if (line.children) {
  23127. var combined = this._recombineShader(line);
  23128. if (combined !== null) {
  23129. result += combined + "\r\n";
  23130. }
  23131. continue;
  23132. }
  23133. if (line.length > 0) {
  23134. result += line + "\r\n";
  23135. }
  23136. }
  23137. return result;
  23138. };
  23139. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  23140. var root = {
  23141. children: []
  23142. };
  23143. var currentNode = root;
  23144. var lines = shaderString.split("\n");
  23145. for (var index = 0; index < lines.length; index++) {
  23146. var line = lines[index].trim();
  23147. // #ifdef
  23148. var pos = line.indexOf("#ifdef ");
  23149. if (pos !== -1) {
  23150. var define = line.substr(pos + 7);
  23151. var newNode = {
  23152. condition: null,
  23153. ndef: false,
  23154. define: define,
  23155. children: [],
  23156. parent: currentNode
  23157. };
  23158. currentNode.children.push(newNode);
  23159. currentNode = newNode;
  23160. continue;
  23161. }
  23162. // #ifndef
  23163. var pos = line.indexOf("#ifndef ");
  23164. if (pos !== -1) {
  23165. var define = line.substr(pos + 8);
  23166. newNode = {
  23167. condition: null,
  23168. define: define,
  23169. ndef: true,
  23170. children: [],
  23171. parent: currentNode
  23172. };
  23173. currentNode.children.push(newNode);
  23174. currentNode = newNode;
  23175. continue;
  23176. }
  23177. // #if
  23178. var pos = line.indexOf("#if ");
  23179. if (pos !== -1) {
  23180. var define = line.substr(pos + 4).trim();
  23181. var conditionPos = define.indexOf(" ");
  23182. newNode = {
  23183. condition: define.substr(conditionPos + 1),
  23184. define: define.substr(0, conditionPos),
  23185. ndef: false,
  23186. children: [],
  23187. parent: currentNode
  23188. };
  23189. currentNode.children.push(newNode);
  23190. currentNode = newNode;
  23191. continue;
  23192. }
  23193. // #endif
  23194. pos = line.indexOf("#endif");
  23195. if (pos !== -1) {
  23196. currentNode = currentNode.parent;
  23197. continue;
  23198. }
  23199. currentNode.children.push(line);
  23200. }
  23201. // Recombine
  23202. return this._recombineShader(root);
  23203. };
  23204. return Effect;
  23205. }());
  23206. Effect._uniqueIdSeed = 0;
  23207. Effect._baseCache = {};
  23208. // Statics
  23209. Effect.ShadersStore = {};
  23210. Effect.IncludesShadersStore = {};
  23211. BABYLON.Effect = Effect;
  23212. })(BABYLON || (BABYLON = {}));
  23213. //# sourceMappingURL=babylon.effect.js.map
  23214. var BABYLON;
  23215. (function (BABYLON) {
  23216. var MaterialHelper = (function () {
  23217. function MaterialHelper() {
  23218. }
  23219. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  23220. if (defines._areMiscDirty) {
  23221. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  23222. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  23223. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  23224. defines["USERIGHTHANDEDSYSTEM"] = scene.useRightHandedSystem;
  23225. }
  23226. };
  23227. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  23228. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  23229. var changed = false;
  23230. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  23231. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  23232. changed = true;
  23233. }
  23234. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  23235. defines["ALPHATEST"] = !defines["ALPHATEST"];
  23236. changed = true;
  23237. }
  23238. if (defines["INSTANCES"] !== useInstances) {
  23239. defines["INSTANCES"] = useInstances;
  23240. changed = true;
  23241. }
  23242. if (changed) {
  23243. defines.markAsUnprocessed();
  23244. }
  23245. };
  23246. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  23247. if (useMorphTargets === void 0) { useMorphTargets = false; }
  23248. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  23249. return false;
  23250. }
  23251. defines._normals = defines._needNormals;
  23252. defines._uvs = defines._needUVs;
  23253. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  23254. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  23255. defines["TANGENT"] = true;
  23256. }
  23257. if (defines._needUVs) {
  23258. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  23259. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  23260. }
  23261. else {
  23262. defines["UV1"] = false;
  23263. defines["UV2"] = false;
  23264. }
  23265. if (useVertexColor) {
  23266. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  23267. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  23268. }
  23269. if (useBones) {
  23270. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  23271. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  23272. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  23273. }
  23274. else {
  23275. defines["NUM_BONE_INFLUENCERS"] = 0;
  23276. defines["BonesPerMesh"] = 0;
  23277. }
  23278. }
  23279. if (useMorphTargets) {
  23280. if (mesh.morphTargetManager) {
  23281. var manager = mesh.morphTargetManager;
  23282. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  23283. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  23284. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  23285. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  23286. }
  23287. else {
  23288. defines["MORPHTARGETS_TANGENT"] = false;
  23289. defines["MORPHTARGETS_NORMAL"] = false;
  23290. defines["MORPHTARGETS"] = false;
  23291. defines["NUM_MORPH_INFLUENCERS"] = 0;
  23292. }
  23293. }
  23294. return true;
  23295. };
  23296. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  23297. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23298. if (disableLighting === void 0) { disableLighting = false; }
  23299. if (!defines._areLightsDirty) {
  23300. return defines._needNormals;
  23301. }
  23302. var lightIndex = 0;
  23303. var needNormals = false;
  23304. var needRebuild = false;
  23305. var lightmapMode = false;
  23306. var shadowEnabled = false;
  23307. var specularEnabled = false;
  23308. if (scene.lightsEnabled && !disableLighting) {
  23309. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  23310. var light = _a[_i];
  23311. needNormals = true;
  23312. if (defines["LIGHT" + lightIndex] === undefined) {
  23313. needRebuild = true;
  23314. }
  23315. defines["LIGHT" + lightIndex] = true;
  23316. defines["SPOTLIGHT" + lightIndex] = false;
  23317. defines["HEMILIGHT" + lightIndex] = false;
  23318. defines["POINTLIGHT" + lightIndex] = false;
  23319. defines["DIRLIGHT" + lightIndex] = false;
  23320. var type;
  23321. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  23322. type = "SPOTLIGHT" + lightIndex;
  23323. }
  23324. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  23325. type = "HEMILIGHT" + lightIndex;
  23326. }
  23327. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  23328. type = "POINTLIGHT" + lightIndex;
  23329. }
  23330. else {
  23331. type = "DIRLIGHT" + lightIndex;
  23332. }
  23333. defines[type] = true;
  23334. // Specular
  23335. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  23336. specularEnabled = true;
  23337. }
  23338. // Shadows
  23339. defines["SHADOW" + lightIndex] = false;
  23340. defines["SHADOWPCF" + lightIndex] = false;
  23341. defines["SHADOWESM" + lightIndex] = false;
  23342. defines["SHADOWCUBE" + lightIndex] = false;
  23343. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  23344. var shadowGenerator = light.getShadowGenerator();
  23345. if (shadowGenerator) {
  23346. shadowEnabled = true;
  23347. shadowGenerator.prepareDefines(defines, lightIndex);
  23348. }
  23349. }
  23350. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  23351. lightmapMode = true;
  23352. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  23353. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  23354. }
  23355. else {
  23356. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  23357. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  23358. }
  23359. lightIndex++;
  23360. if (lightIndex === maxSimultaneousLights)
  23361. break;
  23362. }
  23363. }
  23364. defines["SPECULARTERM"] = specularEnabled;
  23365. defines["SHADOWS"] = shadowEnabled;
  23366. // Resetting all other lights if any
  23367. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  23368. if (defines["LIGHT" + index] !== undefined) {
  23369. defines["LIGHT" + index] = false;
  23370. }
  23371. }
  23372. var caps = scene.getEngine().getCaps();
  23373. if (defines["SHADOWFLOAT"] === undefined) {
  23374. needRebuild = true;
  23375. }
  23376. defines["SHADOWFLOAT"] = shadowEnabled &&
  23377. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  23378. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  23379. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  23380. if (needRebuild) {
  23381. defines.rebuild();
  23382. }
  23383. return needNormals;
  23384. };
  23385. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  23386. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23387. var uniformsList, uniformBuffersList, samplersList, defines;
  23388. if (uniformsListOrOptions.uniformsNames) {
  23389. var options = uniformsListOrOptions;
  23390. uniformsList = options.uniformsNames;
  23391. uniformBuffersList = options.uniformBuffersNames;
  23392. samplersList = options.samplers;
  23393. defines = options.defines;
  23394. maxSimultaneousLights = options.maxSimultaneousLights;
  23395. }
  23396. else {
  23397. uniformsList = uniformsListOrOptions;
  23398. }
  23399. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23400. if (!defines["LIGHT" + lightIndex]) {
  23401. break;
  23402. }
  23403. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  23404. if (uniformBuffersList) {
  23405. uniformBuffersList.push("Light" + lightIndex);
  23406. }
  23407. samplersList.push("shadowSampler" + lightIndex);
  23408. }
  23409. if (defines["NUM_MORPH_INFLUENCERS"]) {
  23410. uniformsList.push("morphTargetInfluences");
  23411. }
  23412. };
  23413. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  23414. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23415. if (!defines["SHADOWS"]) {
  23416. return;
  23417. }
  23418. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23419. if (!defines["LIGHT" + lightIndex]) {
  23420. break;
  23421. }
  23422. if (lightIndex > 0) {
  23423. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  23424. }
  23425. if (defines["SHADOW" + lightIndex]) {
  23426. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  23427. }
  23428. if (defines["SHADOWPCF" + lightIndex]) {
  23429. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  23430. }
  23431. if (defines["SHADOWESM" + lightIndex]) {
  23432. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  23433. }
  23434. }
  23435. };
  23436. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  23437. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  23438. if (influencers > 0) {
  23439. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  23440. var manager = mesh.morphTargetManager;
  23441. var normal = manager.supportsNormals && defines["NORMAL"];
  23442. var tangent = manager.supportsTangents && defines["TANGENT"];
  23443. for (var index = 0; index < influencers; index++) {
  23444. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  23445. if (normal) {
  23446. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  23447. }
  23448. if (tangent) {
  23449. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  23450. }
  23451. if (attribs.length > maxAttributesCount) {
  23452. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  23453. }
  23454. }
  23455. }
  23456. };
  23457. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  23458. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  23459. fallbacks.addCPUSkinningFallback(0, mesh);
  23460. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23461. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23462. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  23463. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  23464. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  23465. }
  23466. }
  23467. };
  23468. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  23469. if (defines["INSTANCES"]) {
  23470. attribs.push("world0");
  23471. attribs.push("world1");
  23472. attribs.push("world2");
  23473. attribs.push("world3");
  23474. }
  23475. };
  23476. // Bindings
  23477. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  23478. if (light.shadowEnabled && mesh.receiveShadows) {
  23479. var shadowGenerator = light.getShadowGenerator();
  23480. if (shadowGenerator) {
  23481. shadowGenerator.bindShadowLight(lightIndex, effect);
  23482. }
  23483. }
  23484. };
  23485. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  23486. light.transferToEffect(effect, lightIndex + "");
  23487. };
  23488. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  23489. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23490. var lightIndex = 0;
  23491. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  23492. var light = _a[_i];
  23493. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  23494. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  23495. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  23496. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], light.range, lightIndex + "");
  23497. if (defines["SPECULARTERM"]) {
  23498. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  23499. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  23500. }
  23501. // Shadows
  23502. if (scene.shadowsEnabled) {
  23503. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  23504. }
  23505. light._uniformBuffer.update();
  23506. lightIndex++;
  23507. if (lightIndex === maxSimultaneousLights)
  23508. break;
  23509. }
  23510. };
  23511. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  23512. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  23513. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  23514. effect.setColor3("vFogColor", scene.fogColor);
  23515. }
  23516. };
  23517. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  23518. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  23519. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  23520. if (matrices) {
  23521. effect.setMatrices("mBones", matrices);
  23522. }
  23523. }
  23524. };
  23525. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  23526. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  23527. return;
  23528. }
  23529. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  23530. };
  23531. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  23532. if (defines["LOGARITHMICDEPTH"]) {
  23533. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  23534. }
  23535. };
  23536. MaterialHelper.BindClipPlane = function (effect, scene) {
  23537. if (scene.clipPlane) {
  23538. var clipPlane = scene.clipPlane;
  23539. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  23540. }
  23541. };
  23542. return MaterialHelper;
  23543. }());
  23544. BABYLON.MaterialHelper = MaterialHelper;
  23545. })(BABYLON || (BABYLON = {}));
  23546. //# sourceMappingURL=babylon.materialHelper.js.map
  23547. var BABYLON;
  23548. (function (BABYLON) {
  23549. var MaterialDefines = (function () {
  23550. function MaterialDefines() {
  23551. this._isDirty = true;
  23552. this._areLightsDirty = true;
  23553. this._areAttributesDirty = true;
  23554. this._areTexturesDirty = true;
  23555. this._areFresnelDirty = true;
  23556. this._areMiscDirty = true;
  23557. this._normals = false;
  23558. this._uvs = false;
  23559. this._needNormals = false;
  23560. this._needUVs = false;
  23561. }
  23562. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  23563. get: function () {
  23564. return this._isDirty;
  23565. },
  23566. enumerable: true,
  23567. configurable: true
  23568. });
  23569. MaterialDefines.prototype.markAsProcessed = function () {
  23570. this._isDirty = false;
  23571. this._areAttributesDirty = false;
  23572. this._areTexturesDirty = false;
  23573. this._areFresnelDirty = false;
  23574. this._areLightsDirty = false;
  23575. this._areMiscDirty = false;
  23576. };
  23577. MaterialDefines.prototype.markAsUnprocessed = function () {
  23578. this._isDirty = true;
  23579. };
  23580. MaterialDefines.prototype.markAllAsDirty = function () {
  23581. this._areTexturesDirty = true;
  23582. this._areAttributesDirty = true;
  23583. this._areLightsDirty = true;
  23584. this._areFresnelDirty = true;
  23585. this._areMiscDirty = true;
  23586. this._isDirty = true;
  23587. };
  23588. MaterialDefines.prototype.markAsLightDirty = function () {
  23589. this._areLightsDirty = true;
  23590. this._isDirty = true;
  23591. };
  23592. MaterialDefines.prototype.markAsAttributesDirty = function () {
  23593. this._areAttributesDirty = true;
  23594. this._isDirty = true;
  23595. };
  23596. MaterialDefines.prototype.markAsTexturesDirty = function () {
  23597. this._areTexturesDirty = true;
  23598. this._isDirty = true;
  23599. };
  23600. MaterialDefines.prototype.markAsFresnelDirty = function () {
  23601. this._areFresnelDirty = true;
  23602. this._isDirty = true;
  23603. };
  23604. MaterialDefines.prototype.markAsMiscDirty = function () {
  23605. this._areMiscDirty = true;
  23606. this._isDirty = true;
  23607. };
  23608. MaterialDefines.prototype.rebuild = function () {
  23609. if (this._keys) {
  23610. delete this._keys;
  23611. }
  23612. this._keys = [];
  23613. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  23614. var key = _a[_i];
  23615. if (key[0] === "_") {
  23616. continue;
  23617. }
  23618. this._keys.push(key);
  23619. }
  23620. };
  23621. MaterialDefines.prototype.isEqual = function (other) {
  23622. if (this._keys.length !== other._keys.length) {
  23623. return false;
  23624. }
  23625. for (var index = 0; index < this._keys.length; index++) {
  23626. var prop = this._keys[index];
  23627. if (this[prop] !== other[prop]) {
  23628. return false;
  23629. }
  23630. }
  23631. return true;
  23632. };
  23633. MaterialDefines.prototype.cloneTo = function (other) {
  23634. if (this._keys.length !== other._keys.length) {
  23635. other._keys = this._keys.slice(0);
  23636. }
  23637. for (var index = 0; index < this._keys.length; index++) {
  23638. var prop = this._keys[index];
  23639. other[prop] = this[prop];
  23640. }
  23641. };
  23642. MaterialDefines.prototype.reset = function () {
  23643. for (var index = 0; index < this._keys.length; index++) {
  23644. var prop = this._keys[index];
  23645. if (typeof (this[prop]) === "number") {
  23646. this[prop] = 0;
  23647. }
  23648. else {
  23649. this[prop] = false;
  23650. }
  23651. }
  23652. };
  23653. MaterialDefines.prototype.toString = function () {
  23654. var result = "";
  23655. for (var index = 0; index < this._keys.length; index++) {
  23656. var prop = this._keys[index];
  23657. var value = this[prop];
  23658. if (typeof (value) === "number") {
  23659. result += "#define " + prop + " " + this[prop] + "\n";
  23660. }
  23661. else if (value) {
  23662. result += "#define " + prop + "\n";
  23663. }
  23664. }
  23665. return result;
  23666. };
  23667. return MaterialDefines;
  23668. }());
  23669. BABYLON.MaterialDefines = MaterialDefines;
  23670. var Material = (function () {
  23671. function Material(name, scene, doNotAdd) {
  23672. this.checkReadyOnEveryCall = false;
  23673. this.checkReadyOnlyOnce = false;
  23674. this.state = "";
  23675. this.alpha = 1.0;
  23676. this._backFaceCulling = true;
  23677. this.doNotSerialize = false;
  23678. this.storeEffectOnSubMeshes = false;
  23679. /**
  23680. * An event triggered when the material is disposed.
  23681. * @type {BABYLON.Observable}
  23682. */
  23683. this.onDisposeObservable = new BABYLON.Observable();
  23684. /**
  23685. * An event triggered when the material is bound.
  23686. * @type {BABYLON.Observable}
  23687. */
  23688. this.onBindObservable = new BABYLON.Observable();
  23689. /**
  23690. * An event triggered when the material is unbound.
  23691. * @type {BABYLON.Observable}
  23692. */
  23693. this.onUnBindObservable = new BABYLON.Observable();
  23694. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  23695. this.disableDepthWrite = false;
  23696. this._fogEnabled = true;
  23697. this.pointSize = 1.0;
  23698. this.zOffset = 0;
  23699. this._wasPreviouslyReady = false;
  23700. this._fillMode = Material.TriangleFillMode;
  23701. this.name = name;
  23702. this.id = name;
  23703. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  23704. if (this._scene.useRightHandedSystem) {
  23705. this.sideOrientation = Material.ClockWiseSideOrientation;
  23706. }
  23707. else {
  23708. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  23709. }
  23710. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  23711. this._useUBO = this.getScene().getEngine().webGLVersion > 1;
  23712. if (!doNotAdd) {
  23713. this._scene.materials.push(this);
  23714. }
  23715. }
  23716. Object.defineProperty(Material, "TriangleFillMode", {
  23717. get: function () {
  23718. return Material._TriangleFillMode;
  23719. },
  23720. enumerable: true,
  23721. configurable: true
  23722. });
  23723. Object.defineProperty(Material, "WireFrameFillMode", {
  23724. get: function () {
  23725. return Material._WireFrameFillMode;
  23726. },
  23727. enumerable: true,
  23728. configurable: true
  23729. });
  23730. Object.defineProperty(Material, "PointFillMode", {
  23731. get: function () {
  23732. return Material._PointFillMode;
  23733. },
  23734. enumerable: true,
  23735. configurable: true
  23736. });
  23737. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  23738. get: function () {
  23739. return Material._ClockWiseSideOrientation;
  23740. },
  23741. enumerable: true,
  23742. configurable: true
  23743. });
  23744. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  23745. get: function () {
  23746. return Material._CounterClockWiseSideOrientation;
  23747. },
  23748. enumerable: true,
  23749. configurable: true
  23750. });
  23751. Object.defineProperty(Material, "TextureDirtyFlag", {
  23752. get: function () {
  23753. return Material._TextureDirtyFlag;
  23754. },
  23755. enumerable: true,
  23756. configurable: true
  23757. });
  23758. Object.defineProperty(Material, "LightDirtyFlag", {
  23759. get: function () {
  23760. return Material._LightDirtyFlag;
  23761. },
  23762. enumerable: true,
  23763. configurable: true
  23764. });
  23765. Object.defineProperty(Material, "FresnelDirtyFlag", {
  23766. get: function () {
  23767. return Material._FresnelDirtyFlag;
  23768. },
  23769. enumerable: true,
  23770. configurable: true
  23771. });
  23772. Object.defineProperty(Material, "AttributesDirtyFlag", {
  23773. get: function () {
  23774. return Material._AttributesDirtyFlag;
  23775. },
  23776. enumerable: true,
  23777. configurable: true
  23778. });
  23779. Object.defineProperty(Material, "MiscDirtyFlag", {
  23780. get: function () {
  23781. return Material._MiscDirtyFlag;
  23782. },
  23783. enumerable: true,
  23784. configurable: true
  23785. });
  23786. Object.defineProperty(Material.prototype, "backFaceCulling", {
  23787. get: function () {
  23788. return this._backFaceCulling;
  23789. },
  23790. set: function (value) {
  23791. if (this._backFaceCulling === value) {
  23792. return;
  23793. }
  23794. this._backFaceCulling = value;
  23795. this.markAsDirty(Material.TextureDirtyFlag);
  23796. },
  23797. enumerable: true,
  23798. configurable: true
  23799. });
  23800. Object.defineProperty(Material.prototype, "onDispose", {
  23801. set: function (callback) {
  23802. if (this._onDisposeObserver) {
  23803. this.onDisposeObservable.remove(this._onDisposeObserver);
  23804. }
  23805. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23806. },
  23807. enumerable: true,
  23808. configurable: true
  23809. });
  23810. Object.defineProperty(Material.prototype, "onBind", {
  23811. set: function (callback) {
  23812. if (this._onBindObserver) {
  23813. this.onBindObservable.remove(this._onBindObserver);
  23814. }
  23815. this._onBindObserver = this.onBindObservable.add(callback);
  23816. },
  23817. enumerable: true,
  23818. configurable: true
  23819. });
  23820. Object.defineProperty(Material.prototype, "fogEnabled", {
  23821. get: function () {
  23822. return this._fogEnabled;
  23823. },
  23824. set: function (value) {
  23825. if (this._fogEnabled === value) {
  23826. return;
  23827. }
  23828. this._fogEnabled = value;
  23829. this.markAsDirty(Material.MiscDirtyFlag);
  23830. },
  23831. enumerable: true,
  23832. configurable: true
  23833. });
  23834. Object.defineProperty(Material.prototype, "wireframe", {
  23835. get: function () {
  23836. return this._fillMode === Material.WireFrameFillMode;
  23837. },
  23838. set: function (value) {
  23839. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  23840. },
  23841. enumerable: true,
  23842. configurable: true
  23843. });
  23844. Object.defineProperty(Material.prototype, "pointsCloud", {
  23845. get: function () {
  23846. return this._fillMode === Material.PointFillMode;
  23847. },
  23848. set: function (value) {
  23849. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  23850. },
  23851. enumerable: true,
  23852. configurable: true
  23853. });
  23854. Object.defineProperty(Material.prototype, "fillMode", {
  23855. get: function () {
  23856. return this._fillMode;
  23857. },
  23858. set: function (value) {
  23859. if (this._fillMode === value) {
  23860. return;
  23861. }
  23862. this._fillMode = value;
  23863. this.markAsDirty(Material.MiscDirtyFlag);
  23864. },
  23865. enumerable: true,
  23866. configurable: true
  23867. });
  23868. /**
  23869. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23870. * subclasses should override adding information pertainent to themselves
  23871. */
  23872. Material.prototype.toString = function (fullDetails) {
  23873. var ret = "Name: " + this.name;
  23874. if (fullDetails) {
  23875. }
  23876. return ret;
  23877. };
  23878. /**
  23879. * Child classes can use it to update shaders
  23880. */
  23881. Material.prototype.markAsDirty = function (flag) {
  23882. };
  23883. Material.prototype.getClassName = function () {
  23884. return "Material";
  23885. };
  23886. Object.defineProperty(Material.prototype, "isFrozen", {
  23887. get: function () {
  23888. return this.checkReadyOnlyOnce;
  23889. },
  23890. enumerable: true,
  23891. configurable: true
  23892. });
  23893. Material.prototype.freeze = function () {
  23894. this.checkReadyOnlyOnce = true;
  23895. };
  23896. Material.prototype.unfreeze = function () {
  23897. this.checkReadyOnlyOnce = false;
  23898. };
  23899. Material.prototype.isReady = function (mesh, useInstances) {
  23900. return true;
  23901. };
  23902. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  23903. return false;
  23904. };
  23905. Material.prototype.getEffect = function () {
  23906. return this._effect;
  23907. };
  23908. Material.prototype.getScene = function () {
  23909. return this._scene;
  23910. };
  23911. Material.prototype.needAlphaBlending = function () {
  23912. return (this.alpha < 1.0);
  23913. };
  23914. Material.prototype.needAlphaTesting = function () {
  23915. return false;
  23916. };
  23917. Material.prototype.getAlphaTestTexture = function () {
  23918. return null;
  23919. };
  23920. Material.prototype.markDirty = function () {
  23921. this._wasPreviouslyReady = false;
  23922. };
  23923. Material.prototype._preBind = function (effect) {
  23924. var engine = this._scene.getEngine();
  23925. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  23926. engine.enableEffect(effect ? effect : this._effect);
  23927. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  23928. };
  23929. Material.prototype.bind = function (world, mesh) {
  23930. };
  23931. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  23932. };
  23933. Material.prototype.bindOnlyWorldMatrix = function (world) {
  23934. };
  23935. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  23936. sceneUbo.bindToEffect(effect, "Scene");
  23937. };
  23938. Material.prototype.bindView = function (effect) {
  23939. if (!this._useUBO) {
  23940. effect.setMatrix("view", this.getScene().getViewMatrix());
  23941. }
  23942. else {
  23943. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  23944. }
  23945. };
  23946. Material.prototype.bindViewProjection = function (effect) {
  23947. if (!this._useUBO) {
  23948. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  23949. }
  23950. else {
  23951. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  23952. }
  23953. };
  23954. Material.prototype._afterBind = function (mesh) {
  23955. this._scene._cachedMaterial = this;
  23956. this.onBindObservable.notifyObservers(mesh);
  23957. if (this.disableDepthWrite) {
  23958. var engine = this._scene.getEngine();
  23959. this._cachedDepthWriteState = engine.getDepthWrite();
  23960. engine.setDepthWrite(false);
  23961. }
  23962. };
  23963. Material.prototype.unbind = function () {
  23964. this.onUnBindObservable.notifyObservers(this);
  23965. if (this.disableDepthWrite) {
  23966. var engine = this._scene.getEngine();
  23967. engine.setDepthWrite(this._cachedDepthWriteState);
  23968. }
  23969. };
  23970. Material.prototype.clone = function (name) {
  23971. return null;
  23972. };
  23973. Material.prototype.getBindedMeshes = function () {
  23974. var result = new Array();
  23975. for (var index = 0; index < this._scene.meshes.length; index++) {
  23976. var mesh = this._scene.meshes[index];
  23977. if (mesh.material === this) {
  23978. result.push(mesh);
  23979. }
  23980. }
  23981. return result;
  23982. };
  23983. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  23984. // Animations
  23985. this.getScene().stopAnimation(this);
  23986. // Remove from scene
  23987. var index = this._scene.materials.indexOf(this);
  23988. if (index >= 0) {
  23989. this._scene.materials.splice(index, 1);
  23990. }
  23991. // Remove from meshes
  23992. for (index = 0; index < this._scene.meshes.length; index++) {
  23993. var mesh = this._scene.meshes[index];
  23994. if (mesh.material === this) {
  23995. mesh.material = null;
  23996. if (mesh.geometry) {
  23997. var geometry = mesh.geometry;
  23998. if (this.storeEffectOnSubMeshes) {
  23999. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  24000. var subMesh = _a[_i];
  24001. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  24002. }
  24003. }
  24004. else {
  24005. geometry._releaseVertexArrayObject(this._effect);
  24006. }
  24007. }
  24008. }
  24009. }
  24010. this._uniformBuffer.dispose();
  24011. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  24012. if (forceDisposeEffect && this._effect) {
  24013. if (this.storeEffectOnSubMeshes) {
  24014. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24015. var subMesh = _c[_b];
  24016. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  24017. }
  24018. }
  24019. else {
  24020. this._scene.getEngine()._releaseEffect(this._effect);
  24021. }
  24022. this._effect = null;
  24023. }
  24024. // Callback
  24025. this.onDisposeObservable.notifyObservers(this);
  24026. this.onDisposeObservable.clear();
  24027. this.onBindObservable.clear();
  24028. this.onUnBindObservable.clear();
  24029. };
  24030. Material.prototype.serialize = function () {
  24031. return BABYLON.SerializationHelper.Serialize(this);
  24032. };
  24033. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  24034. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  24035. multiMaterial.id = parsedMultiMaterial.id;
  24036. if (BABYLON.Tags) {
  24037. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  24038. }
  24039. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  24040. var subMatId = parsedMultiMaterial.materials[matIndex];
  24041. if (subMatId) {
  24042. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  24043. }
  24044. else {
  24045. multiMaterial.subMaterials.push(null);
  24046. }
  24047. }
  24048. return multiMaterial;
  24049. };
  24050. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  24051. if (!parsedMaterial.customType) {
  24052. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  24053. }
  24054. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && !parsedMaterial.overloadedAlbedo) {
  24055. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  24056. if (!BABYLON.LegacyPBRMaterial) {
  24057. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  24058. return;
  24059. }
  24060. }
  24061. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  24062. return materialType.Parse(parsedMaterial, scene, rootUrl);
  24063. ;
  24064. };
  24065. return Material;
  24066. }());
  24067. Material._TriangleFillMode = 0;
  24068. Material._WireFrameFillMode = 1;
  24069. Material._PointFillMode = 2;
  24070. Material._ClockWiseSideOrientation = 0;
  24071. Material._CounterClockWiseSideOrientation = 1;
  24072. Material._TextureDirtyFlag = 1;
  24073. Material._LightDirtyFlag = 2;
  24074. Material._FresnelDirtyFlag = 4;
  24075. Material._AttributesDirtyFlag = 8;
  24076. Material._MiscDirtyFlag = 16;
  24077. __decorate([
  24078. BABYLON.serialize()
  24079. ], Material.prototype, "id", void 0);
  24080. __decorate([
  24081. BABYLON.serialize()
  24082. ], Material.prototype, "name", void 0);
  24083. __decorate([
  24084. BABYLON.serialize()
  24085. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  24086. __decorate([
  24087. BABYLON.serialize()
  24088. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  24089. __decorate([
  24090. BABYLON.serialize()
  24091. ], Material.prototype, "state", void 0);
  24092. __decorate([
  24093. BABYLON.serialize()
  24094. ], Material.prototype, "alpha", void 0);
  24095. __decorate([
  24096. BABYLON.serialize("backFaceCulling")
  24097. ], Material.prototype, "_backFaceCulling", void 0);
  24098. __decorate([
  24099. BABYLON.serialize()
  24100. ], Material.prototype, "sideOrientation", void 0);
  24101. __decorate([
  24102. BABYLON.serialize()
  24103. ], Material.prototype, "alphaMode", void 0);
  24104. __decorate([
  24105. BABYLON.serialize()
  24106. ], Material.prototype, "disableDepthWrite", void 0);
  24107. __decorate([
  24108. BABYLON.serialize("fogEnabled")
  24109. ], Material.prototype, "_fogEnabled", void 0);
  24110. __decorate([
  24111. BABYLON.serialize()
  24112. ], Material.prototype, "pointSize", void 0);
  24113. __decorate([
  24114. BABYLON.serialize()
  24115. ], Material.prototype, "zOffset", void 0);
  24116. __decorate([
  24117. BABYLON.serialize()
  24118. ], Material.prototype, "wireframe", null);
  24119. __decorate([
  24120. BABYLON.serialize()
  24121. ], Material.prototype, "pointsCloud", null);
  24122. __decorate([
  24123. BABYLON.serialize()
  24124. ], Material.prototype, "fillMode", null);
  24125. BABYLON.Material = Material;
  24126. })(BABYLON || (BABYLON = {}));
  24127. //# sourceMappingURL=babylon.material.js.map
  24128. var BABYLON;
  24129. (function (BABYLON) {
  24130. var UniformBuffer = (function () {
  24131. /**
  24132. * Uniform buffer objects.
  24133. *
  24134. * Handles blocks of uniform on the GPU.
  24135. *
  24136. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  24137. *
  24138. * For more information, please refer to :
  24139. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  24140. */
  24141. function UniformBuffer(engine, data, dynamic) {
  24142. this._engine = engine;
  24143. this._noUBO = engine.webGLVersion === 1;
  24144. this._dynamic = dynamic;
  24145. this._data = data || [];
  24146. this._uniformLocations = {};
  24147. this._uniformSizes = {};
  24148. this._uniformLocationPointer = 0;
  24149. this._needSync = false;
  24150. if (this._noUBO) {
  24151. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  24152. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  24153. this.updateFloat = this._updateFloatForEffect;
  24154. this.updateFloat2 = this._updateFloat2ForEffect;
  24155. this.updateFloat3 = this._updateFloat3ForEffect;
  24156. this.updateFloat4 = this._updateFloat4ForEffect;
  24157. this.updateMatrix = this._updateMatrixForEffect;
  24158. this.updateVector3 = this._updateVector3ForEffect;
  24159. this.updateVector4 = this._updateVector4ForEffect;
  24160. this.updateColor3 = this._updateColor3ForEffect;
  24161. this.updateColor4 = this._updateColor4ForEffect;
  24162. }
  24163. else {
  24164. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  24165. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  24166. this.updateFloat = this._updateFloatForUniform;
  24167. this.updateFloat2 = this._updateFloat2ForUniform;
  24168. this.updateFloat3 = this._updateFloat3ForUniform;
  24169. this.updateFloat4 = this._updateFloat4ForUniform;
  24170. this.updateMatrix = this._updateMatrixForUniform;
  24171. this.updateVector3 = this._updateVector3ForUniform;
  24172. this.updateVector4 = this._updateVector4ForUniform;
  24173. this.updateColor3 = this._updateColor3ForUniform;
  24174. this.updateColor4 = this._updateColor4ForUniform;
  24175. }
  24176. }
  24177. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  24178. // Properties
  24179. /**
  24180. * Indicates if the buffer is using the WebGL2 UBO implementation,
  24181. * or just falling back on setUniformXXX calls.
  24182. */
  24183. get: function () {
  24184. return !this._noUBO;
  24185. },
  24186. enumerable: true,
  24187. configurable: true
  24188. });
  24189. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  24190. /**
  24191. * Indicates if the WebGL underlying uniform buffer is in sync
  24192. * with the javascript cache data.
  24193. */
  24194. get: function () {
  24195. return !this._needSync;
  24196. },
  24197. enumerable: true,
  24198. configurable: true
  24199. });
  24200. /**
  24201. * Indicates if the WebGL underlying uniform buffer is dynamic.
  24202. * Also, a dynamic UniformBuffer will disable cache verification and always
  24203. * update the underlying WebGL uniform buffer to the GPU.
  24204. */
  24205. UniformBuffer.prototype.isDynamic = function () {
  24206. return this._dynamic;
  24207. };
  24208. /**
  24209. * The data cache on JS side.
  24210. */
  24211. UniformBuffer.prototype.getData = function () {
  24212. return this._bufferData;
  24213. };
  24214. /**
  24215. * The underlying WebGL Uniform buffer.
  24216. */
  24217. UniformBuffer.prototype.getBuffer = function () {
  24218. return this._buffer;
  24219. };
  24220. /**
  24221. * std140 layout specifies how to align data within an UBO structure.
  24222. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  24223. * for specs.
  24224. */
  24225. UniformBuffer.prototype._fillAlignment = function (size) {
  24226. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  24227. // and 4x4 matrices
  24228. // TODO : change if other types are used
  24229. var alignment;
  24230. if (size <= 2) {
  24231. alignment = size;
  24232. }
  24233. else {
  24234. alignment = 4;
  24235. }
  24236. if ((this._uniformLocationPointer % alignment) !== 0) {
  24237. var oldPointer = this._uniformLocationPointer;
  24238. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  24239. var diff = this._uniformLocationPointer - oldPointer;
  24240. for (var i = 0; i < diff; i++) {
  24241. this._data.push(0);
  24242. }
  24243. }
  24244. };
  24245. /**
  24246. * Adds an uniform in the buffer.
  24247. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  24248. * for the layout to be correct !
  24249. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24250. * @param {number|number[]} size Data size, or data directly.
  24251. */
  24252. UniformBuffer.prototype.addUniform = function (name, size) {
  24253. if (this._noUBO) {
  24254. return;
  24255. }
  24256. if (this._uniformLocations[name] !== undefined) {
  24257. // Already existing uniform
  24258. return;
  24259. }
  24260. // This function must be called in the order of the shader layout !
  24261. // size can be the size of the uniform, or data directly
  24262. var data;
  24263. if (size instanceof Array) {
  24264. data = size;
  24265. size = data.length;
  24266. }
  24267. else {
  24268. size = size;
  24269. data = [];
  24270. // Fill with zeros
  24271. for (var i = 0; i < size; i++) {
  24272. data.push(0);
  24273. }
  24274. }
  24275. this._fillAlignment(size);
  24276. this._uniformSizes[name] = size;
  24277. this._uniformLocations[name] = this._uniformLocationPointer;
  24278. this._uniformLocationPointer += size;
  24279. for (var i = 0; i < size; i++) {
  24280. this._data.push(data[i]);
  24281. }
  24282. this._needSync = true;
  24283. };
  24284. /**
  24285. * Wrapper for addUniform.
  24286. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24287. * @param {Matrix} mat A 4x4 matrix.
  24288. */
  24289. UniformBuffer.prototype.addMatrix = function (name, mat) {
  24290. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  24291. };
  24292. /**
  24293. * Wrapper for addUniform.
  24294. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24295. * @param {number} x
  24296. * @param {number} y
  24297. */
  24298. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  24299. var temp = [x, y];
  24300. this.addUniform(name, temp);
  24301. };
  24302. /**
  24303. * Wrapper for addUniform.
  24304. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24305. * @param {number} x
  24306. * @param {number} y
  24307. * @param {number} z
  24308. */
  24309. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  24310. var temp = [x, y, z];
  24311. this.addUniform(name, temp);
  24312. };
  24313. /**
  24314. * Wrapper for addUniform.
  24315. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24316. * @param {Color3} color
  24317. */
  24318. UniformBuffer.prototype.addColor3 = function (name, color) {
  24319. var temp = [];
  24320. color.toArray(temp);
  24321. this.addUniform(name, temp);
  24322. };
  24323. /**
  24324. * Wrapper for addUniform.
  24325. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24326. * @param {Color3} color
  24327. * @param {number} alpha
  24328. */
  24329. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  24330. var temp = [];
  24331. color.toArray(temp);
  24332. temp.push(alpha);
  24333. this.addUniform(name, temp);
  24334. };
  24335. /**
  24336. * Wrapper for addUniform.
  24337. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24338. * @param {Vector3} vector
  24339. */
  24340. UniformBuffer.prototype.addVector3 = function (name, vector) {
  24341. var temp = [];
  24342. vector.toArray(temp);
  24343. this.addUniform(name, temp);
  24344. };
  24345. /**
  24346. * Wrapper for addUniform.
  24347. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24348. */
  24349. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  24350. this.addUniform(name, 12);
  24351. };
  24352. /**
  24353. * Wrapper for addUniform.
  24354. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24355. */
  24356. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  24357. this.addUniform(name, 8);
  24358. };
  24359. /**
  24360. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  24361. */
  24362. UniformBuffer.prototype.create = function () {
  24363. if (this._noUBO) {
  24364. return;
  24365. }
  24366. if (this._buffer) {
  24367. return; // nothing to do
  24368. }
  24369. // See spec, alignment must be filled as a vec4
  24370. this._fillAlignment(4);
  24371. this._bufferData = new Float32Array(this._data);
  24372. if (this._dynamic) {
  24373. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  24374. }
  24375. else {
  24376. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  24377. }
  24378. this._needSync = true;
  24379. };
  24380. /**
  24381. * Updates the WebGL Uniform Buffer on the GPU.
  24382. * If the `dynamic` flag is set to true, no cache comparison is done.
  24383. * Otherwise, the buffer will be updated only if the cache differs.
  24384. */
  24385. UniformBuffer.prototype.update = function () {
  24386. if (!this._buffer) {
  24387. this.create();
  24388. return;
  24389. }
  24390. if (!this._dynamic && !this._needSync) {
  24391. return;
  24392. }
  24393. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  24394. this._needSync = false;
  24395. };
  24396. /**
  24397. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  24398. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  24399. * @param {number[]|Float32Array} data Flattened data
  24400. * @param {number} size Size of the data.
  24401. */
  24402. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  24403. var location = this._uniformLocations[uniformName];
  24404. if (location === undefined) {
  24405. if (this._buffer) {
  24406. // Cannot add an uniform if the buffer is already created
  24407. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  24408. return;
  24409. }
  24410. this.addUniform(uniformName, size);
  24411. location = this._uniformLocations[uniformName];
  24412. }
  24413. if (!this._buffer) {
  24414. this.create();
  24415. }
  24416. if (!this._dynamic) {
  24417. // Cache for static uniform buffers
  24418. var changed = false;
  24419. for (var i = 0; i < size; i++) {
  24420. if (this._bufferData[location + i] !== data[i]) {
  24421. changed = true;
  24422. this._bufferData[location + i] = data[i];
  24423. }
  24424. }
  24425. this._needSync = this._needSync || changed;
  24426. }
  24427. else {
  24428. // No cache for dynamic
  24429. for (var i = 0; i < size; i++) {
  24430. this._bufferData[location + i] = data[i];
  24431. }
  24432. }
  24433. };
  24434. // Update methods
  24435. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  24436. // To match std140, matrix must be realigned
  24437. for (var i = 0; i < 3; i++) {
  24438. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  24439. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  24440. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  24441. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  24442. }
  24443. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  24444. };
  24445. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  24446. this._currentEffect.setMatrix3x3(name, matrix);
  24447. };
  24448. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  24449. this._currentEffect.setMatrix2x2(name, matrix);
  24450. };
  24451. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  24452. // To match std140, matrix must be realigned
  24453. for (var i = 0; i < 2; i++) {
  24454. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  24455. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  24456. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  24457. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  24458. }
  24459. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  24460. };
  24461. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  24462. this._currentEffect.setFloat(name, x);
  24463. };
  24464. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  24465. UniformBuffer._tempBuffer[0] = x;
  24466. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  24467. };
  24468. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  24469. if (suffix === void 0) { suffix = ""; }
  24470. this._currentEffect.setFloat2(name + suffix, x, y);
  24471. };
  24472. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  24473. if (suffix === void 0) { suffix = ""; }
  24474. UniformBuffer._tempBuffer[0] = x;
  24475. UniformBuffer._tempBuffer[1] = y;
  24476. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  24477. };
  24478. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  24479. if (suffix === void 0) { suffix = ""; }
  24480. this._currentEffect.setFloat3(name + suffix, x, y, z);
  24481. };
  24482. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  24483. if (suffix === void 0) { suffix = ""; }
  24484. UniformBuffer._tempBuffer[0] = x;
  24485. UniformBuffer._tempBuffer[1] = y;
  24486. UniformBuffer._tempBuffer[2] = z;
  24487. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24488. };
  24489. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  24490. if (suffix === void 0) { suffix = ""; }
  24491. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  24492. };
  24493. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  24494. if (suffix === void 0) { suffix = ""; }
  24495. UniformBuffer._tempBuffer[0] = x;
  24496. UniformBuffer._tempBuffer[1] = y;
  24497. UniformBuffer._tempBuffer[2] = z;
  24498. UniformBuffer._tempBuffer[3] = w;
  24499. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24500. };
  24501. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  24502. this._currentEffect.setMatrix(name, mat);
  24503. };
  24504. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  24505. this.updateUniform(name, mat.toArray(), 16);
  24506. };
  24507. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  24508. this._currentEffect.setVector3(name, vector);
  24509. };
  24510. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  24511. vector.toArray(UniformBuffer._tempBuffer);
  24512. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24513. };
  24514. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  24515. this._currentEffect.setVector4(name, vector);
  24516. };
  24517. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  24518. vector.toArray(UniformBuffer._tempBuffer);
  24519. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24520. };
  24521. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  24522. if (suffix === void 0) { suffix = ""; }
  24523. this._currentEffect.setColor3(name + suffix, color);
  24524. };
  24525. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  24526. if (suffix === void 0) { suffix = ""; }
  24527. color.toArray(UniformBuffer._tempBuffer);
  24528. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24529. };
  24530. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  24531. if (suffix === void 0) { suffix = ""; }
  24532. this._currentEffect.setColor4(name + suffix, color, alpha);
  24533. };
  24534. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  24535. if (suffix === void 0) { suffix = ""; }
  24536. color.toArray(UniformBuffer._tempBuffer);
  24537. UniformBuffer._tempBuffer[3] = alpha;
  24538. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24539. };
  24540. /**
  24541. * Sets a sampler uniform on the effect.
  24542. * @param {string} name Name of the sampler.
  24543. * @param {Texture} texture
  24544. */
  24545. UniformBuffer.prototype.setTexture = function (name, texture) {
  24546. this._currentEffect.setTexture(name, texture);
  24547. };
  24548. /**
  24549. * Directly updates the value of the uniform in the cache AND on the GPU.
  24550. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  24551. * @param {number[]|Float32Array} data Flattened data
  24552. */
  24553. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  24554. this.updateUniform(uniformName, data, data.length);
  24555. this.update();
  24556. };
  24557. /**
  24558. * Binds this uniform buffer to an effect.
  24559. * @param {Effect} effect
  24560. * @param {string} name Name of the uniform block in the shader.
  24561. */
  24562. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  24563. this._currentEffect = effect;
  24564. if (this._noUBO) {
  24565. return;
  24566. }
  24567. effect.bindUniformBuffer(this._buffer, name);
  24568. };
  24569. /**
  24570. * Disposes the uniform buffer.
  24571. */
  24572. UniformBuffer.prototype.dispose = function () {
  24573. if (!this._buffer) {
  24574. return;
  24575. }
  24576. if (this._engine._releaseBuffer(this._buffer)) {
  24577. this._buffer = null;
  24578. }
  24579. };
  24580. return UniformBuffer;
  24581. }());
  24582. // Pool for avoiding memory leaks
  24583. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  24584. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  24585. BABYLON.UniformBuffer = UniformBuffer;
  24586. })(BABYLON || (BABYLON = {}));
  24587. //# sourceMappingURL=babylon.uniformBuffer.js.map
  24588. var BABYLON;
  24589. (function (BABYLON) {
  24590. var PushMaterial = (function (_super) {
  24591. __extends(PushMaterial, _super);
  24592. function PushMaterial(name, scene) {
  24593. var _this = _super.call(this, name, scene) || this;
  24594. _this.storeEffectOnSubMeshes = true;
  24595. return _this;
  24596. }
  24597. PushMaterial.prototype.getEffect = function () {
  24598. return this._activeEffect;
  24599. };
  24600. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  24601. if (!mesh) {
  24602. return false;
  24603. }
  24604. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  24605. return true;
  24606. }
  24607. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  24608. };
  24609. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  24610. this._activeEffect.setMatrix("world", world);
  24611. };
  24612. PushMaterial.prototype.bind = function (world, mesh) {
  24613. if (!mesh) {
  24614. return;
  24615. }
  24616. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  24617. };
  24618. PushMaterial.prototype._afterBind = function (mesh, effect) {
  24619. _super.prototype._afterBind.call(this, mesh);
  24620. this.getScene()._cachedEffect = effect;
  24621. };
  24622. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  24623. if (visibility === void 0) { visibility = 0; }
  24624. return scene.isCachedMaterialValid(this, effect, visibility);
  24625. };
  24626. PushMaterial.prototype.markAsDirty = function (flag) {
  24627. if (flag & BABYLON.Material.TextureDirtyFlag) {
  24628. this._markAllSubMeshesAsTexturesDirty();
  24629. }
  24630. if (flag & BABYLON.Material.LightDirtyFlag) {
  24631. this._markAllSubMeshesAsLightsDirty();
  24632. }
  24633. if (flag & BABYLON.Material.FresnelDirtyFlag) {
  24634. this._markAllSubMeshesAsFresnelDirty();
  24635. }
  24636. if (flag & BABYLON.Material.AttributesDirtyFlag) {
  24637. this._markAllSubMeshesAsAttributesDirty();
  24638. }
  24639. if (flag & BABYLON.Material.MiscDirtyFlag) {
  24640. this._markAllSubMeshesAsMiscDirty();
  24641. }
  24642. this.getScene().resetCachedMaterial();
  24643. };
  24644. PushMaterial.prototype._markAllSubMeshesAsDirty = function (func) {
  24645. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  24646. var mesh = _a[_i];
  24647. if (!mesh.subMeshes) {
  24648. continue;
  24649. }
  24650. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24651. var subMesh = _c[_b];
  24652. if (subMesh.getMaterial() !== this) {
  24653. continue;
  24654. }
  24655. if (!subMesh._materialDefines) {
  24656. return;
  24657. }
  24658. func(subMesh._materialDefines);
  24659. }
  24660. }
  24661. };
  24662. PushMaterial.prototype._markAllSubMeshesAsTexturesDirty = function () {
  24663. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  24664. };
  24665. PushMaterial.prototype._markAllSubMeshesAsFresnelDirty = function () {
  24666. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  24667. };
  24668. PushMaterial.prototype._markAllSubMeshesAsLightsDirty = function () {
  24669. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  24670. };
  24671. PushMaterial.prototype._markAllSubMeshesAsAttributesDirty = function () {
  24672. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  24673. };
  24674. PushMaterial.prototype._markAllSubMeshesAsMiscDirty = function () {
  24675. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  24676. };
  24677. return PushMaterial;
  24678. }(BABYLON.Material));
  24679. BABYLON.PushMaterial = PushMaterial;
  24680. })(BABYLON || (BABYLON = {}));
  24681. //# sourceMappingURL=babylon.pushMaterial.js.map
  24682. var BABYLON;
  24683. (function (BABYLON) {
  24684. var VertexData = (function () {
  24685. function VertexData() {
  24686. }
  24687. VertexData.prototype.set = function (data, kind) {
  24688. switch (kind) {
  24689. case BABYLON.VertexBuffer.PositionKind:
  24690. this.positions = data;
  24691. break;
  24692. case BABYLON.VertexBuffer.NormalKind:
  24693. this.normals = data;
  24694. break;
  24695. case BABYLON.VertexBuffer.TangentKind:
  24696. this.tangents = data;
  24697. break;
  24698. case BABYLON.VertexBuffer.UVKind:
  24699. this.uvs = data;
  24700. break;
  24701. case BABYLON.VertexBuffer.UV2Kind:
  24702. this.uvs2 = data;
  24703. break;
  24704. case BABYLON.VertexBuffer.UV3Kind:
  24705. this.uvs3 = data;
  24706. break;
  24707. case BABYLON.VertexBuffer.UV4Kind:
  24708. this.uvs4 = data;
  24709. break;
  24710. case BABYLON.VertexBuffer.UV5Kind:
  24711. this.uvs5 = data;
  24712. break;
  24713. case BABYLON.VertexBuffer.UV6Kind:
  24714. this.uvs6 = data;
  24715. break;
  24716. case BABYLON.VertexBuffer.ColorKind:
  24717. this.colors = data;
  24718. break;
  24719. case BABYLON.VertexBuffer.MatricesIndicesKind:
  24720. this.matricesIndices = data;
  24721. break;
  24722. case BABYLON.VertexBuffer.MatricesWeightsKind:
  24723. this.matricesWeights = data;
  24724. break;
  24725. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  24726. this.matricesIndicesExtra = data;
  24727. break;
  24728. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  24729. this.matricesWeightsExtra = data;
  24730. break;
  24731. }
  24732. };
  24733. /**
  24734. * Associates the vertexData to the passed Mesh.
  24735. * Sets it as updatable or not (default `false`).
  24736. * Returns the VertexData.
  24737. */
  24738. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  24739. this._applyTo(mesh, updatable);
  24740. return this;
  24741. };
  24742. /**
  24743. * Associates the vertexData to the passed Geometry.
  24744. * Sets it as updatable or not (default `false`).
  24745. * Returns the VertexData.
  24746. */
  24747. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  24748. this._applyTo(geometry, updatable);
  24749. return this;
  24750. };
  24751. /**
  24752. * Updates the associated mesh.
  24753. * Returns the VertexData.
  24754. */
  24755. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  24756. this._update(mesh);
  24757. return this;
  24758. };
  24759. /**
  24760. * Updates the associated geometry.
  24761. * Returns the VertexData.
  24762. */
  24763. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  24764. this._update(geometry);
  24765. return this;
  24766. };
  24767. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  24768. if (this.positions) {
  24769. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  24770. }
  24771. if (this.normals) {
  24772. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  24773. }
  24774. if (this.tangents) {
  24775. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  24776. }
  24777. if (this.uvs) {
  24778. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  24779. }
  24780. if (this.uvs2) {
  24781. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  24782. }
  24783. if (this.uvs3) {
  24784. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  24785. }
  24786. if (this.uvs4) {
  24787. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  24788. }
  24789. if (this.uvs5) {
  24790. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  24791. }
  24792. if (this.uvs6) {
  24793. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  24794. }
  24795. if (this.colors) {
  24796. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  24797. }
  24798. if (this.matricesIndices) {
  24799. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  24800. }
  24801. if (this.matricesWeights) {
  24802. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  24803. }
  24804. if (this.matricesIndicesExtra) {
  24805. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  24806. }
  24807. if (this.matricesWeightsExtra) {
  24808. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  24809. }
  24810. if (this.indices) {
  24811. meshOrGeometry.setIndices(this.indices);
  24812. }
  24813. return this;
  24814. };
  24815. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  24816. if (this.positions) {
  24817. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  24818. }
  24819. if (this.normals) {
  24820. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  24821. }
  24822. if (this.tangents) {
  24823. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  24824. }
  24825. if (this.uvs) {
  24826. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  24827. }
  24828. if (this.uvs2) {
  24829. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  24830. }
  24831. if (this.uvs3) {
  24832. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  24833. }
  24834. if (this.uvs4) {
  24835. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  24836. }
  24837. if (this.uvs5) {
  24838. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  24839. }
  24840. if (this.uvs6) {
  24841. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  24842. }
  24843. if (this.colors) {
  24844. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  24845. }
  24846. if (this.matricesIndices) {
  24847. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  24848. }
  24849. if (this.matricesWeights) {
  24850. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  24851. }
  24852. if (this.matricesIndicesExtra) {
  24853. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  24854. }
  24855. if (this.matricesWeightsExtra) {
  24856. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  24857. }
  24858. if (this.indices) {
  24859. meshOrGeometry.setIndices(this.indices);
  24860. }
  24861. return this;
  24862. };
  24863. /**
  24864. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  24865. * Returns the VertexData.
  24866. */
  24867. VertexData.prototype.transform = function (matrix) {
  24868. var transformed = BABYLON.Vector3.Zero();
  24869. var index;
  24870. if (this.positions) {
  24871. var position = BABYLON.Vector3.Zero();
  24872. for (index = 0; index < this.positions.length; index += 3) {
  24873. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  24874. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  24875. this.positions[index] = transformed.x;
  24876. this.positions[index + 1] = transformed.y;
  24877. this.positions[index + 2] = transformed.z;
  24878. }
  24879. }
  24880. if (this.normals) {
  24881. var normal = BABYLON.Vector3.Zero();
  24882. for (index = 0; index < this.normals.length; index += 3) {
  24883. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  24884. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  24885. this.normals[index] = transformed.x;
  24886. this.normals[index + 1] = transformed.y;
  24887. this.normals[index + 2] = transformed.z;
  24888. }
  24889. }
  24890. if (this.tangents) {
  24891. var tangent = BABYLON.Vector4.Zero();
  24892. var tangentTransformed = BABYLON.Vector4.Zero();
  24893. for (index = 0; index < this.tangents.length; index += 4) {
  24894. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  24895. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  24896. this.tangents[index] = tangentTransformed.x;
  24897. this.tangents[index + 1] = tangentTransformed.y;
  24898. this.tangents[index + 2] = tangentTransformed.z;
  24899. this.tangents[index + 3] = tangentTransformed.w;
  24900. }
  24901. }
  24902. return this;
  24903. };
  24904. /**
  24905. * Merges the passed VertexData into the current one.
  24906. * Returns the modified VertexData.
  24907. */
  24908. VertexData.prototype.merge = function (other) {
  24909. if (other.indices) {
  24910. if (!this.indices) {
  24911. this.indices = [];
  24912. }
  24913. var offset = this.positions ? this.positions.length / 3 : 0;
  24914. for (var index = 0; index < other.indices.length; index++) {
  24915. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  24916. this.indices.push(other.indices[index] + offset);
  24917. }
  24918. }
  24919. this.positions = this._mergeElement(this.positions, other.positions);
  24920. this.normals = this._mergeElement(this.normals, other.normals);
  24921. this.tangents = this._mergeElement(this.tangents, other.tangents);
  24922. this.uvs = this._mergeElement(this.uvs, other.uvs);
  24923. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  24924. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  24925. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  24926. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  24927. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  24928. this.colors = this._mergeElement(this.colors, other.colors);
  24929. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  24930. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  24931. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  24932. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  24933. return this;
  24934. };
  24935. VertexData.prototype._mergeElement = function (source, other) {
  24936. if (!other)
  24937. return source;
  24938. if (!source)
  24939. return other;
  24940. var len = other.length + source.length;
  24941. var isSrcTypedArray = source instanceof Float32Array;
  24942. var isOthTypedArray = other instanceof Float32Array;
  24943. // use non-loop method when the source is Float32Array
  24944. if (isSrcTypedArray) {
  24945. var ret32 = new Float32Array(len);
  24946. ret32.set(source);
  24947. ret32.set(other, source.length);
  24948. return ret32;
  24949. // source is number[], when other is also use concat
  24950. }
  24951. else if (!isOthTypedArray) {
  24952. return source.concat(other);
  24953. // source is a number[], but other is a Float32Array, loop required
  24954. }
  24955. else {
  24956. var ret = source.slice(0); // copy source to a separate array
  24957. for (var i = 0, len = other.length; i < len; i++) {
  24958. ret.push(other[i]);
  24959. }
  24960. return ret;
  24961. }
  24962. };
  24963. /**
  24964. * Serializes the VertexData.
  24965. * Returns a serialized object.
  24966. */
  24967. VertexData.prototype.serialize = function () {
  24968. var serializationObject = this.serialize();
  24969. if (this.positions) {
  24970. serializationObject.positions = this.positions;
  24971. }
  24972. if (this.normals) {
  24973. serializationObject.normals = this.normals;
  24974. }
  24975. if (this.tangents) {
  24976. serializationObject.tangents = this.tangents;
  24977. }
  24978. if (this.uvs) {
  24979. serializationObject.uvs = this.uvs;
  24980. }
  24981. if (this.uvs2) {
  24982. serializationObject.uvs2 = this.uvs2;
  24983. }
  24984. if (this.uvs3) {
  24985. serializationObject.uvs3 = this.uvs3;
  24986. }
  24987. if (this.uvs4) {
  24988. serializationObject.uvs4 = this.uvs4;
  24989. }
  24990. if (this.uvs5) {
  24991. serializationObject.uvs5 = this.uvs5;
  24992. }
  24993. if (this.uvs6) {
  24994. serializationObject.uvs6 = this.uvs6;
  24995. }
  24996. if (this.colors) {
  24997. serializationObject.colors = this.colors;
  24998. }
  24999. if (this.matricesIndices) {
  25000. serializationObject.matricesIndices = this.matricesIndices;
  25001. serializationObject.matricesIndices._isExpanded = true;
  25002. }
  25003. if (this.matricesWeights) {
  25004. serializationObject.matricesWeights = this.matricesWeights;
  25005. }
  25006. if (this.matricesIndicesExtra) {
  25007. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  25008. serializationObject.matricesIndicesExtra._isExpanded = true;
  25009. }
  25010. if (this.matricesWeightsExtra) {
  25011. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  25012. }
  25013. serializationObject.indices = this.indices;
  25014. return serializationObject;
  25015. };
  25016. // Statics
  25017. /**
  25018. * Returns the object VertexData associated to the passed mesh.
  25019. */
  25020. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  25021. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  25022. };
  25023. /**
  25024. * Returns the object VertexData associated to the passed geometry.
  25025. */
  25026. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  25027. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  25028. };
  25029. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  25030. var result = new VertexData();
  25031. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25032. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  25033. }
  25034. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25035. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  25036. }
  25037. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  25038. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  25039. }
  25040. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25041. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  25042. }
  25043. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25044. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  25045. }
  25046. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  25047. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  25048. }
  25049. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  25050. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  25051. }
  25052. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  25053. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  25054. }
  25055. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  25056. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  25057. }
  25058. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  25059. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  25060. }
  25061. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25062. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  25063. }
  25064. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25065. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  25066. }
  25067. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  25068. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  25069. }
  25070. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  25071. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  25072. }
  25073. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  25074. return result;
  25075. };
  25076. /**
  25077. * Creates the vertexData of the Ribbon.
  25078. */
  25079. VertexData.CreateRibbon = function (options) {
  25080. var pathArray = options.pathArray;
  25081. var closeArray = options.closeArray || false;
  25082. var closePath = options.closePath || false;
  25083. var invertUV = options.invertUV || false;
  25084. var defaultOffset = Math.floor(pathArray[0].length / 2);
  25085. var offset = options.offset || defaultOffset;
  25086. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  25087. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25088. var customUV = options.uvs;
  25089. var customColors = options.colors;
  25090. var positions = [];
  25091. var indices = [];
  25092. var normals = [];
  25093. var uvs = [];
  25094. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  25095. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  25096. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  25097. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  25098. var minlg; // minimal length among all paths from pathArray
  25099. var lg = []; // array of path lengths : nb of vertex per path
  25100. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  25101. var p; // path iterator
  25102. var i; // point iterator
  25103. var j; // point iterator
  25104. // if single path in pathArray
  25105. if (pathArray.length < 2) {
  25106. var ar1 = [];
  25107. var ar2 = [];
  25108. for (i = 0; i < pathArray[0].length - offset; i++) {
  25109. ar1.push(pathArray[0][i]);
  25110. ar2.push(pathArray[0][i + offset]);
  25111. }
  25112. pathArray = [ar1, ar2];
  25113. }
  25114. // positions and horizontal distances (u)
  25115. var idc = 0;
  25116. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  25117. var path;
  25118. var l;
  25119. minlg = pathArray[0].length;
  25120. var vectlg;
  25121. var dist;
  25122. for (p = 0; p < pathArray.length; p++) {
  25123. uTotalDistance[p] = 0;
  25124. us[p] = [0];
  25125. path = pathArray[p];
  25126. l = path.length;
  25127. minlg = (minlg < l) ? minlg : l;
  25128. j = 0;
  25129. while (j < l) {
  25130. positions.push(path[j].x, path[j].y, path[j].z);
  25131. if (j > 0) {
  25132. vectlg = path[j].subtract(path[j - 1]).length();
  25133. dist = vectlg + uTotalDistance[p];
  25134. us[p].push(dist);
  25135. uTotalDistance[p] = dist;
  25136. }
  25137. j++;
  25138. }
  25139. if (closePath) {
  25140. j--;
  25141. positions.push(path[0].x, path[0].y, path[0].z);
  25142. vectlg = path[j].subtract(path[0]).length();
  25143. dist = vectlg + uTotalDistance[p];
  25144. us[p].push(dist);
  25145. uTotalDistance[p] = dist;
  25146. }
  25147. lg[p] = l + closePathCorr;
  25148. idx[p] = idc;
  25149. idc += (l + closePathCorr);
  25150. }
  25151. // vertical distances (v)
  25152. var path1;
  25153. var path2;
  25154. var vertex1;
  25155. var vertex2;
  25156. for (i = 0; i < minlg + closePathCorr; i++) {
  25157. vTotalDistance[i] = 0;
  25158. vs[i] = [0];
  25159. for (p = 0; p < pathArray.length - 1; p++) {
  25160. path1 = pathArray[p];
  25161. path2 = pathArray[p + 1];
  25162. if (i === minlg) {
  25163. vertex1 = path1[0];
  25164. vertex2 = path2[0];
  25165. }
  25166. else {
  25167. vertex1 = path1[i];
  25168. vertex2 = path2[i];
  25169. }
  25170. vectlg = vertex2.subtract(vertex1).length();
  25171. dist = vectlg + vTotalDistance[i];
  25172. vs[i].push(dist);
  25173. vTotalDistance[i] = dist;
  25174. }
  25175. if (closeArray) {
  25176. path1 = pathArray[p];
  25177. path2 = pathArray[0];
  25178. if (i === minlg) {
  25179. vertex2 = path2[0];
  25180. }
  25181. vectlg = vertex2.subtract(vertex1).length();
  25182. dist = vectlg + vTotalDistance[i];
  25183. vTotalDistance[i] = dist;
  25184. }
  25185. }
  25186. // uvs
  25187. var u;
  25188. var v;
  25189. if (customUV) {
  25190. for (p = 0; p < customUV.length; p++) {
  25191. uvs.push(customUV[p].x, customUV[p].y);
  25192. }
  25193. }
  25194. else {
  25195. for (p = 0; p < pathArray.length; p++) {
  25196. for (i = 0; i < minlg + closePathCorr; i++) {
  25197. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  25198. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  25199. if (invertUV) {
  25200. uvs.push(v, u);
  25201. }
  25202. else {
  25203. uvs.push(u, v);
  25204. }
  25205. }
  25206. }
  25207. }
  25208. // indices
  25209. p = 0; // path index
  25210. var pi = 0; // positions array index
  25211. var l1 = lg[p] - 1; // path1 length
  25212. var l2 = lg[p + 1] - 1; // path2 length
  25213. var min = (l1 < l2) ? l1 : l2; // current path stop index
  25214. var shft = idx[1] - idx[0]; // shift
  25215. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  25216. while (pi <= min && p < path1nb) {
  25217. // 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
  25218. indices.push(pi, pi + shft, pi + 1);
  25219. indices.push(pi + shft + 1, pi + 1, pi + shft);
  25220. pi += 1;
  25221. if (pi === min) {
  25222. p++;
  25223. if (p === lg.length - 1) {
  25224. shft = idx[0] - idx[p];
  25225. l1 = lg[p] - 1;
  25226. l2 = lg[0] - 1;
  25227. }
  25228. else {
  25229. shft = idx[p + 1] - idx[p];
  25230. l1 = lg[p] - 1;
  25231. l2 = lg[p + 1] - 1;
  25232. }
  25233. pi = idx[p];
  25234. min = (l1 < l2) ? l1 + pi : l2 + pi;
  25235. }
  25236. }
  25237. // normals
  25238. VertexData.ComputeNormals(positions, indices, normals);
  25239. if (closePath) {
  25240. var indexFirst = 0;
  25241. var indexLast = 0;
  25242. for (p = 0; p < pathArray.length; p++) {
  25243. indexFirst = idx[p] * 3;
  25244. if (p + 1 < pathArray.length) {
  25245. indexLast = (idx[p + 1] - 1) * 3;
  25246. }
  25247. else {
  25248. indexLast = normals.length - 3;
  25249. }
  25250. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  25251. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  25252. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  25253. normals[indexLast] = normals[indexFirst];
  25254. normals[indexLast + 1] = normals[indexFirst + 1];
  25255. normals[indexLast + 2] = normals[indexFirst + 2];
  25256. }
  25257. }
  25258. // sides
  25259. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25260. // Colors
  25261. if (customColors) {
  25262. var colors = new Float32Array(customColors.length * 4);
  25263. for (var c = 0; c < customColors.length; c++) {
  25264. colors[c * 4] = customColors[c].r;
  25265. colors[c * 4 + 1] = customColors[c].g;
  25266. colors[c * 4 + 2] = customColors[c].b;
  25267. colors[c * 4 + 3] = customColors[c].a;
  25268. }
  25269. }
  25270. // Result
  25271. var vertexData = new VertexData();
  25272. var positions32 = new Float32Array(positions);
  25273. var normals32 = new Float32Array(normals);
  25274. var uvs32 = new Float32Array(uvs);
  25275. vertexData.indices = indices;
  25276. vertexData.positions = positions32;
  25277. vertexData.normals = normals32;
  25278. vertexData.uvs = uvs32;
  25279. if (customColors) {
  25280. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  25281. }
  25282. if (closePath) {
  25283. vertexData._idx = idx;
  25284. }
  25285. return vertexData;
  25286. };
  25287. /**
  25288. * Creates the VertexData of the Box.
  25289. */
  25290. VertexData.CreateBox = function (options) {
  25291. var normalsSource = [
  25292. new BABYLON.Vector3(0, 0, 1),
  25293. new BABYLON.Vector3(0, 0, -1),
  25294. new BABYLON.Vector3(1, 0, 0),
  25295. new BABYLON.Vector3(-1, 0, 0),
  25296. new BABYLON.Vector3(0, 1, 0),
  25297. new BABYLON.Vector3(0, -1, 0)
  25298. ];
  25299. var indices = [];
  25300. var positions = [];
  25301. var normals = [];
  25302. var uvs = [];
  25303. var width = options.width || options.size || 1;
  25304. var height = options.height || options.size || 1;
  25305. var depth = options.depth || options.size || 1;
  25306. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25307. var faceUV = options.faceUV || new Array(6);
  25308. var faceColors = options.faceColors;
  25309. var colors = [];
  25310. // default face colors and UV if undefined
  25311. for (var f = 0; f < 6; f++) {
  25312. if (faceUV[f] === undefined) {
  25313. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25314. }
  25315. if (faceColors && faceColors[f] === undefined) {
  25316. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25317. }
  25318. }
  25319. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  25320. // Create each face in turn.
  25321. for (var index = 0; index < normalsSource.length; index++) {
  25322. var normal = normalsSource[index];
  25323. // Get two vectors perpendicular to the face normal and to each other.
  25324. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  25325. var side2 = BABYLON.Vector3.Cross(normal, side1);
  25326. // Six indices (two triangles) per face.
  25327. var verticesLength = positions.length / 3;
  25328. indices.push(verticesLength);
  25329. indices.push(verticesLength + 1);
  25330. indices.push(verticesLength + 2);
  25331. indices.push(verticesLength);
  25332. indices.push(verticesLength + 2);
  25333. indices.push(verticesLength + 3);
  25334. // Four vertices per face.
  25335. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  25336. positions.push(vertex.x, vertex.y, vertex.z);
  25337. normals.push(normal.x, normal.y, normal.z);
  25338. uvs.push(faceUV[index].z, faceUV[index].w);
  25339. if (faceColors) {
  25340. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25341. }
  25342. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  25343. positions.push(vertex.x, vertex.y, vertex.z);
  25344. normals.push(normal.x, normal.y, normal.z);
  25345. uvs.push(faceUV[index].x, faceUV[index].w);
  25346. if (faceColors) {
  25347. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25348. }
  25349. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  25350. positions.push(vertex.x, vertex.y, vertex.z);
  25351. normals.push(normal.x, normal.y, normal.z);
  25352. uvs.push(faceUV[index].x, faceUV[index].y);
  25353. if (faceColors) {
  25354. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25355. }
  25356. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  25357. positions.push(vertex.x, vertex.y, vertex.z);
  25358. normals.push(normal.x, normal.y, normal.z);
  25359. uvs.push(faceUV[index].z, faceUV[index].y);
  25360. if (faceColors) {
  25361. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25362. }
  25363. }
  25364. // sides
  25365. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25366. // Result
  25367. var vertexData = new VertexData();
  25368. vertexData.indices = indices;
  25369. vertexData.positions = positions;
  25370. vertexData.normals = normals;
  25371. vertexData.uvs = uvs;
  25372. if (faceColors) {
  25373. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  25374. vertexData.colors = totalColors;
  25375. }
  25376. return vertexData;
  25377. };
  25378. /**
  25379. * Creates the VertexData of the Sphere.
  25380. */
  25381. VertexData.CreateSphere = function (options) {
  25382. var segments = options.segments || 32;
  25383. var diameterX = options.diameterX || options.diameter || 1;
  25384. var diameterY = options.diameterY || options.diameter || 1;
  25385. var diameterZ = options.diameterZ || options.diameter || 1;
  25386. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25387. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  25388. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25389. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  25390. var totalZRotationSteps = 2 + segments;
  25391. var totalYRotationSteps = 2 * totalZRotationSteps;
  25392. var indices = [];
  25393. var positions = [];
  25394. var normals = [];
  25395. var uvs = [];
  25396. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  25397. var normalizedZ = zRotationStep / totalZRotationSteps;
  25398. var angleZ = normalizedZ * Math.PI * slice;
  25399. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  25400. var normalizedY = yRotationStep / totalYRotationSteps;
  25401. var angleY = normalizedY * Math.PI * 2 * arc;
  25402. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  25403. var rotationY = BABYLON.Matrix.RotationY(angleY);
  25404. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  25405. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  25406. var vertex = complete.multiply(radius);
  25407. var normal = complete.divide(radius).normalize();
  25408. positions.push(vertex.x, vertex.y, vertex.z);
  25409. normals.push(normal.x, normal.y, normal.z);
  25410. uvs.push(normalizedY, normalizedZ);
  25411. }
  25412. if (zRotationStep > 0) {
  25413. var verticesCount = positions.length / 3;
  25414. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  25415. indices.push((firstIndex));
  25416. indices.push((firstIndex + 1));
  25417. indices.push(firstIndex + totalYRotationSteps + 1);
  25418. indices.push((firstIndex + totalYRotationSteps + 1));
  25419. indices.push((firstIndex + 1));
  25420. indices.push((firstIndex + totalYRotationSteps + 2));
  25421. }
  25422. }
  25423. }
  25424. // Sides
  25425. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25426. // Result
  25427. var vertexData = new VertexData();
  25428. vertexData.indices = indices;
  25429. vertexData.positions = positions;
  25430. vertexData.normals = normals;
  25431. vertexData.uvs = uvs;
  25432. return vertexData;
  25433. };
  25434. /**
  25435. * Creates the VertexData of the Cylinder or Cone.
  25436. */
  25437. VertexData.CreateCylinder = function (options) {
  25438. var height = options.height || 2;
  25439. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  25440. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  25441. var tessellation = options.tessellation || 24;
  25442. var subdivisions = options.subdivisions || 1;
  25443. var hasRings = options.hasRings;
  25444. var enclose = options.enclose;
  25445. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25446. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25447. var faceUV = options.faceUV || new Array(3);
  25448. var faceColors = options.faceColors;
  25449. // default face colors and UV if undefined
  25450. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  25451. var ringNb = (hasRings) ? subdivisions : 1;
  25452. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  25453. var f;
  25454. for (f = 0; f < surfaceNb; f++) {
  25455. if (faceColors && faceColors[f] === undefined) {
  25456. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25457. }
  25458. }
  25459. for (f = 0; f < surfaceNb; f++) {
  25460. if (faceUV && faceUV[f] === undefined) {
  25461. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25462. }
  25463. }
  25464. var indices = [];
  25465. var positions = [];
  25466. var normals = [];
  25467. var uvs = [];
  25468. var colors = [];
  25469. var angle_step = Math.PI * 2 * arc / tessellation;
  25470. var angle;
  25471. var h;
  25472. var radius;
  25473. var tan = (diameterBottom - diameterTop) / 2 / height;
  25474. var ringVertex = BABYLON.Vector3.Zero();
  25475. var ringNormal = BABYLON.Vector3.Zero();
  25476. var ringFirstVertex = BABYLON.Vector3.Zero();
  25477. var ringFirstNormal = BABYLON.Vector3.Zero();
  25478. var quadNormal = BABYLON.Vector3.Zero();
  25479. var Y = BABYLON.Axis.Y;
  25480. // positions, normals, uvs
  25481. var i;
  25482. var j;
  25483. var r;
  25484. var ringIdx = 1;
  25485. var s = 1; // surface index
  25486. var cs = 0;
  25487. var v = 0;
  25488. for (i = 0; i <= subdivisions; i++) {
  25489. h = i / subdivisions;
  25490. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  25491. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  25492. for (r = 0; r < ringIdx; r++) {
  25493. if (hasRings) {
  25494. s += r;
  25495. }
  25496. if (enclose) {
  25497. s += 2 * r;
  25498. }
  25499. for (j = 0; j <= tessellation; j++) {
  25500. angle = j * angle_step;
  25501. // position
  25502. ringVertex.x = Math.cos(-angle) * radius;
  25503. ringVertex.y = -height / 2 + h * height;
  25504. ringVertex.z = Math.sin(-angle) * radius;
  25505. // normal
  25506. if (diameterTop === 0 && i === subdivisions) {
  25507. // if no top cap, reuse former normals
  25508. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  25509. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  25510. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  25511. }
  25512. else {
  25513. ringNormal.x = ringVertex.x;
  25514. ringNormal.z = ringVertex.z;
  25515. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  25516. ringNormal.normalize();
  25517. }
  25518. // keep first ring vertex values for enclose
  25519. if (j === 0) {
  25520. ringFirstVertex.copyFrom(ringVertex);
  25521. ringFirstNormal.copyFrom(ringNormal);
  25522. }
  25523. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25524. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  25525. if (hasRings) {
  25526. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  25527. }
  25528. else {
  25529. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  25530. }
  25531. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  25532. if (faceColors) {
  25533. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  25534. }
  25535. }
  25536. // if enclose, add four vertices and their dedicated normals
  25537. if (arc !== 1 && enclose) {
  25538. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25539. positions.push(0, ringVertex.y, 0);
  25540. positions.push(0, ringVertex.y, 0);
  25541. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  25542. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  25543. quadNormal.normalize();
  25544. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25545. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  25546. quadNormal.normalize();
  25547. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25548. if (hasRings) {
  25549. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  25550. }
  25551. else {
  25552. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  25553. }
  25554. uvs.push(faceUV[s + 1].x, v);
  25555. uvs.push(faceUV[s + 1].z, v);
  25556. if (hasRings) {
  25557. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  25558. }
  25559. else {
  25560. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  25561. }
  25562. uvs.push(faceUV[s + 2].x, v);
  25563. uvs.push(faceUV[s + 2].z, v);
  25564. if (faceColors) {
  25565. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25566. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25567. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25568. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25569. }
  25570. }
  25571. if (cs !== s) {
  25572. cs = s;
  25573. }
  25574. }
  25575. }
  25576. // indices
  25577. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  25578. var s;
  25579. i = 0;
  25580. for (s = 0; s < subdivisions; s++) {
  25581. for (j = 0; j < tessellation; j++) {
  25582. var i0 = i * (e + 1) + j;
  25583. var i1 = (i + 1) * (e + 1) + j;
  25584. var i2 = i * (e + 1) + (j + 1);
  25585. var i3 = (i + 1) * (e + 1) + (j + 1);
  25586. indices.push(i0, i1, i2);
  25587. indices.push(i3, i2, i1);
  25588. }
  25589. if (arc !== 1 && enclose) {
  25590. indices.push(i0 + 2, i1 + 2, i2 + 2);
  25591. indices.push(i3 + 2, i2 + 2, i1 + 2);
  25592. indices.push(i0 + 4, i1 + 4, i2 + 4);
  25593. indices.push(i3 + 4, i2 + 4, i1 + 4);
  25594. }
  25595. i = (hasRings) ? (i + 2) : (i + 1);
  25596. }
  25597. // Caps
  25598. var createCylinderCap = function (isTop) {
  25599. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  25600. if (radius === 0) {
  25601. return;
  25602. }
  25603. // Cap positions, normals & uvs
  25604. var angle;
  25605. var circleVector;
  25606. var i;
  25607. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  25608. var c;
  25609. if (faceColors) {
  25610. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  25611. }
  25612. // cap center
  25613. var vbase = positions.length / 3;
  25614. var offset = isTop ? height / 2 : -height / 2;
  25615. var center = new BABYLON.Vector3(0, offset, 0);
  25616. positions.push(center.x, center.y, center.z);
  25617. normals.push(0, isTop ? 1 : -1, 0);
  25618. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  25619. if (faceColors) {
  25620. colors.push(c.r, c.g, c.b, c.a);
  25621. }
  25622. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  25623. for (i = 0; i <= tessellation; i++) {
  25624. angle = Math.PI * 2 * i * arc / tessellation;
  25625. var cos = Math.cos(-angle);
  25626. var sin = Math.sin(-angle);
  25627. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  25628. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  25629. positions.push(circleVector.x, circleVector.y, circleVector.z);
  25630. normals.push(0, isTop ? 1 : -1, 0);
  25631. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  25632. if (faceColors) {
  25633. colors.push(c.r, c.g, c.b, c.a);
  25634. }
  25635. }
  25636. // Cap indices
  25637. for (i = 0; i < tessellation; i++) {
  25638. if (!isTop) {
  25639. indices.push(vbase);
  25640. indices.push(vbase + (i + 1));
  25641. indices.push(vbase + (i + 2));
  25642. }
  25643. else {
  25644. indices.push(vbase);
  25645. indices.push(vbase + (i + 2));
  25646. indices.push(vbase + (i + 1));
  25647. }
  25648. }
  25649. };
  25650. // add caps to geometry
  25651. createCylinderCap(false);
  25652. createCylinderCap(true);
  25653. // Sides
  25654. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25655. var vertexData = new VertexData();
  25656. vertexData.indices = indices;
  25657. vertexData.positions = positions;
  25658. vertexData.normals = normals;
  25659. vertexData.uvs = uvs;
  25660. if (faceColors) {
  25661. vertexData.colors = colors;
  25662. }
  25663. return vertexData;
  25664. };
  25665. /**
  25666. * Creates the VertexData of the Torus.
  25667. */
  25668. VertexData.CreateTorus = function (options) {
  25669. var indices = [];
  25670. var positions = [];
  25671. var normals = [];
  25672. var uvs = [];
  25673. var diameter = options.diameter || 1;
  25674. var thickness = options.thickness || 0.5;
  25675. var tessellation = options.tessellation || 16;
  25676. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25677. var stride = tessellation + 1;
  25678. for (var i = 0; i <= tessellation; i++) {
  25679. var u = i / tessellation;
  25680. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  25681. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  25682. for (var j = 0; j <= tessellation; j++) {
  25683. var v = 1 - j / tessellation;
  25684. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  25685. var dx = Math.cos(innerAngle);
  25686. var dy = Math.sin(innerAngle);
  25687. // Create a vertex.
  25688. var normal = new BABYLON.Vector3(dx, dy, 0);
  25689. var position = normal.scale(thickness / 2);
  25690. var textureCoordinate = new BABYLON.Vector2(u, v);
  25691. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  25692. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  25693. positions.push(position.x, position.y, position.z);
  25694. normals.push(normal.x, normal.y, normal.z);
  25695. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25696. // And create indices for two triangles.
  25697. var nextI = (i + 1) % stride;
  25698. var nextJ = (j + 1) % stride;
  25699. indices.push(i * stride + j);
  25700. indices.push(i * stride + nextJ);
  25701. indices.push(nextI * stride + j);
  25702. indices.push(i * stride + nextJ);
  25703. indices.push(nextI * stride + nextJ);
  25704. indices.push(nextI * stride + j);
  25705. }
  25706. }
  25707. // Sides
  25708. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25709. // Result
  25710. var vertexData = new VertexData();
  25711. vertexData.indices = indices;
  25712. vertexData.positions = positions;
  25713. vertexData.normals = normals;
  25714. vertexData.uvs = uvs;
  25715. return vertexData;
  25716. };
  25717. /**
  25718. * Creates the VertexData of the LineSystem.
  25719. */
  25720. VertexData.CreateLineSystem = function (options) {
  25721. var indices = [];
  25722. var positions = [];
  25723. var lines = options.lines;
  25724. var idx = 0;
  25725. for (var l = 0; l < lines.length; l++) {
  25726. var points = lines[l];
  25727. for (var index = 0; index < points.length; index++) {
  25728. positions.push(points[index].x, points[index].y, points[index].z);
  25729. if (index > 0) {
  25730. indices.push(idx - 1);
  25731. indices.push(idx);
  25732. }
  25733. idx++;
  25734. }
  25735. }
  25736. var vertexData = new VertexData();
  25737. vertexData.indices = indices;
  25738. vertexData.positions = positions;
  25739. return vertexData;
  25740. };
  25741. /**
  25742. * Create the VertexData of the DashedLines.
  25743. */
  25744. VertexData.CreateDashedLines = function (options) {
  25745. var dashSize = options.dashSize || 3;
  25746. var gapSize = options.gapSize || 1;
  25747. var dashNb = options.dashNb || 200;
  25748. var points = options.points;
  25749. var positions = new Array();
  25750. var indices = new Array();
  25751. var curvect = BABYLON.Vector3.Zero();
  25752. var lg = 0;
  25753. var nb = 0;
  25754. var shft = 0;
  25755. var dashshft = 0;
  25756. var curshft = 0;
  25757. var idx = 0;
  25758. var i = 0;
  25759. for (i = 0; i < points.length - 1; i++) {
  25760. points[i + 1].subtractToRef(points[i], curvect);
  25761. lg += curvect.length();
  25762. }
  25763. shft = lg / dashNb;
  25764. dashshft = dashSize * shft / (dashSize + gapSize);
  25765. for (i = 0; i < points.length - 1; i++) {
  25766. points[i + 1].subtractToRef(points[i], curvect);
  25767. nb = Math.floor(curvect.length() / shft);
  25768. curvect.normalize();
  25769. for (var j = 0; j < nb; j++) {
  25770. curshft = shft * j;
  25771. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  25772. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  25773. indices.push(idx, idx + 1);
  25774. idx += 2;
  25775. }
  25776. }
  25777. // Result
  25778. var vertexData = new VertexData();
  25779. vertexData.positions = positions;
  25780. vertexData.indices = indices;
  25781. return vertexData;
  25782. };
  25783. /**
  25784. * Creates the VertexData of the Ground.
  25785. */
  25786. VertexData.CreateGround = function (options) {
  25787. var indices = [];
  25788. var positions = [];
  25789. var normals = [];
  25790. var uvs = [];
  25791. var row, col;
  25792. var width = options.width || 1;
  25793. var height = options.height || 1;
  25794. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  25795. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  25796. for (row = 0; row <= subdivisionsY; row++) {
  25797. for (col = 0; col <= subdivisionsX; col++) {
  25798. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  25799. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25800. positions.push(position.x, position.y, position.z);
  25801. normals.push(normal.x, normal.y, normal.z);
  25802. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  25803. }
  25804. }
  25805. for (row = 0; row < subdivisionsY; row++) {
  25806. for (col = 0; col < subdivisionsX; col++) {
  25807. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  25808. indices.push(col + 1 + row * (subdivisionsX + 1));
  25809. indices.push(col + row * (subdivisionsX + 1));
  25810. indices.push(col + (row + 1) * (subdivisionsX + 1));
  25811. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  25812. indices.push(col + row * (subdivisionsX + 1));
  25813. }
  25814. }
  25815. // Result
  25816. var vertexData = new VertexData();
  25817. vertexData.indices = indices;
  25818. vertexData.positions = positions;
  25819. vertexData.normals = normals;
  25820. vertexData.uvs = uvs;
  25821. return vertexData;
  25822. };
  25823. /**
  25824. * Creates the VertexData of the TiledGround.
  25825. */
  25826. VertexData.CreateTiledGround = function (options) {
  25827. var xmin = options.xmin || -1.0;
  25828. var zmin = options.zmin || -1.0;
  25829. var xmax = options.xmax || 1.0;
  25830. var zmax = options.zmax || 1.0;
  25831. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  25832. var precision = options.precision || { w: 1, h: 1 };
  25833. var indices = [];
  25834. var positions = [];
  25835. var normals = [];
  25836. var uvs = [];
  25837. var row, col, tileRow, tileCol;
  25838. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  25839. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  25840. precision.w = (precision.w < 1) ? 1 : precision.w;
  25841. precision.h = (precision.h < 1) ? 1 : precision.h;
  25842. var tileSize = {
  25843. 'w': (xmax - xmin) / subdivisions.w,
  25844. 'h': (zmax - zmin) / subdivisions.h
  25845. };
  25846. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  25847. // Indices
  25848. var base = positions.length / 3;
  25849. var rowLength = precision.w + 1;
  25850. for (row = 0; row < precision.h; row++) {
  25851. for (col = 0; col < precision.w; col++) {
  25852. var square = [
  25853. base + col + row * rowLength,
  25854. base + (col + 1) + row * rowLength,
  25855. base + (col + 1) + (row + 1) * rowLength,
  25856. base + col + (row + 1) * rowLength
  25857. ];
  25858. indices.push(square[1]);
  25859. indices.push(square[2]);
  25860. indices.push(square[3]);
  25861. indices.push(square[0]);
  25862. indices.push(square[1]);
  25863. indices.push(square[3]);
  25864. }
  25865. }
  25866. // Position, normals and uvs
  25867. var position = BABYLON.Vector3.Zero();
  25868. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25869. for (row = 0; row <= precision.h; row++) {
  25870. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  25871. for (col = 0; col <= precision.w; col++) {
  25872. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  25873. position.y = 0;
  25874. positions.push(position.x, position.y, position.z);
  25875. normals.push(normal.x, normal.y, normal.z);
  25876. uvs.push(col / precision.w, row / precision.h);
  25877. }
  25878. }
  25879. }
  25880. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  25881. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  25882. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  25883. }
  25884. }
  25885. // Result
  25886. var vertexData = new VertexData();
  25887. vertexData.indices = indices;
  25888. vertexData.positions = positions;
  25889. vertexData.normals = normals;
  25890. vertexData.uvs = uvs;
  25891. return vertexData;
  25892. };
  25893. /**
  25894. * Creates the VertexData of the Ground designed from a heightmap.
  25895. */
  25896. VertexData.CreateGroundFromHeightMap = function (options) {
  25897. var indices = [];
  25898. var positions = [];
  25899. var normals = [];
  25900. var uvs = [];
  25901. var row, col;
  25902. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  25903. // Vertices
  25904. for (row = 0; row <= options.subdivisions; row++) {
  25905. for (col = 0; col <= options.subdivisions; col++) {
  25906. 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));
  25907. // Compute height
  25908. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  25909. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  25910. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  25911. var r = options.buffer[pos] / 255.0;
  25912. var g = options.buffer[pos + 1] / 255.0;
  25913. var b = options.buffer[pos + 2] / 255.0;
  25914. var gradient = r * filter.r + g * filter.g + b * filter.b;
  25915. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  25916. // Add vertex
  25917. positions.push(position.x, position.y, position.z);
  25918. normals.push(0, 0, 0);
  25919. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  25920. }
  25921. }
  25922. // Indices
  25923. for (row = 0; row < options.subdivisions; row++) {
  25924. for (col = 0; col < options.subdivisions; col++) {
  25925. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25926. indices.push(col + 1 + row * (options.subdivisions + 1));
  25927. indices.push(col + row * (options.subdivisions + 1));
  25928. indices.push(col + (row + 1) * (options.subdivisions + 1));
  25929. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25930. indices.push(col + row * (options.subdivisions + 1));
  25931. }
  25932. }
  25933. // Normals
  25934. VertexData.ComputeNormals(positions, indices, normals);
  25935. // Result
  25936. var vertexData = new VertexData();
  25937. vertexData.indices = indices;
  25938. vertexData.positions = positions;
  25939. vertexData.normals = normals;
  25940. vertexData.uvs = uvs;
  25941. return vertexData;
  25942. };
  25943. /**
  25944. * Creates the VertexData of the Plane.
  25945. */
  25946. VertexData.CreatePlane = function (options) {
  25947. var indices = [];
  25948. var positions = [];
  25949. var normals = [];
  25950. var uvs = [];
  25951. var width = options.width || options.size || 1;
  25952. var height = options.height || options.size || 1;
  25953. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25954. // Vertices
  25955. var halfWidth = width / 2.0;
  25956. var halfHeight = height / 2.0;
  25957. positions.push(-halfWidth, -halfHeight, 0);
  25958. normals.push(0, 0, -1.0);
  25959. uvs.push(0.0, 0.0);
  25960. positions.push(halfWidth, -halfHeight, 0);
  25961. normals.push(0, 0, -1.0);
  25962. uvs.push(1.0, 0.0);
  25963. positions.push(halfWidth, halfHeight, 0);
  25964. normals.push(0, 0, -1.0);
  25965. uvs.push(1.0, 1.0);
  25966. positions.push(-halfWidth, halfHeight, 0);
  25967. normals.push(0, 0, -1.0);
  25968. uvs.push(0.0, 1.0);
  25969. // Indices
  25970. indices.push(0);
  25971. indices.push(1);
  25972. indices.push(2);
  25973. indices.push(0);
  25974. indices.push(2);
  25975. indices.push(3);
  25976. // Sides
  25977. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25978. // Result
  25979. var vertexData = new VertexData();
  25980. vertexData.indices = indices;
  25981. vertexData.positions = positions;
  25982. vertexData.normals = normals;
  25983. vertexData.uvs = uvs;
  25984. return vertexData;
  25985. };
  25986. /**
  25987. * Creates the VertexData of the Disc or regular Polygon.
  25988. */
  25989. VertexData.CreateDisc = function (options) {
  25990. var positions = [];
  25991. var indices = [];
  25992. var normals = [];
  25993. var uvs = [];
  25994. var radius = options.radius || 0.5;
  25995. var tessellation = options.tessellation || 64;
  25996. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25997. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25998. // positions and uvs
  25999. positions.push(0, 0, 0); // disc center first
  26000. uvs.push(0.5, 0.5);
  26001. var theta = Math.PI * 2 * arc;
  26002. var step = theta / tessellation;
  26003. for (var a = 0; a < theta; a += step) {
  26004. var x = Math.cos(a);
  26005. var y = Math.sin(a);
  26006. var u = (x + 1) / 2;
  26007. var v = (1 - y) / 2;
  26008. positions.push(radius * x, radius * y, 0);
  26009. uvs.push(u, v);
  26010. }
  26011. if (arc === 1) {
  26012. positions.push(positions[3], positions[4], positions[5]); // close the circle
  26013. uvs.push(uvs[2], uvs[3]);
  26014. }
  26015. //indices
  26016. var vertexNb = positions.length / 3;
  26017. for (var i = 1; i < vertexNb - 1; i++) {
  26018. indices.push(i + 1, 0, i);
  26019. }
  26020. // result
  26021. VertexData.ComputeNormals(positions, indices, normals);
  26022. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26023. var vertexData = new VertexData();
  26024. vertexData.indices = indices;
  26025. vertexData.positions = positions;
  26026. vertexData.normals = normals;
  26027. vertexData.uvs = uvs;
  26028. return vertexData;
  26029. };
  26030. /**
  26031. * Re-creates the VertexData of the Polygon for sideOrientation.
  26032. */
  26033. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  26034. var faceUV = fUV || new Array(3);
  26035. var faceColors = fColors;
  26036. var colors = [];
  26037. // default face colors and UV if undefined
  26038. for (var f = 0; f < 3; f++) {
  26039. if (faceUV[f] === undefined) {
  26040. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26041. }
  26042. if (faceColors && faceColors[f] === undefined) {
  26043. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26044. }
  26045. }
  26046. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26047. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26048. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26049. var indices = polygon.getIndices();
  26050. // set face colours and textures
  26051. var idx = 0;
  26052. var face = 0;
  26053. for (var index = 0; index < normals.length; index += 3) {
  26054. //Edge Face no. 1
  26055. if (Math.abs(normals[index + 1]) == 0) {
  26056. face = 1;
  26057. }
  26058. //Top Face no. 0
  26059. if (normals[index + 1] == 1) {
  26060. face = 0;
  26061. }
  26062. //Bottom Face no. 2
  26063. if (normals[index + 1] == -1) {
  26064. face = 2;
  26065. }
  26066. idx = index / 3;
  26067. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  26068. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  26069. if (faceColors) {
  26070. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  26071. }
  26072. }
  26073. // sides
  26074. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  26075. // Result
  26076. var vertexData = new VertexData();
  26077. vertexData.indices = indices;
  26078. vertexData.positions = positions;
  26079. vertexData.normals = normals;
  26080. vertexData.uvs = uvs;
  26081. if (faceColors) {
  26082. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26083. vertexData.colors = totalColors;
  26084. }
  26085. return vertexData;
  26086. };
  26087. /**
  26088. * Creates the VertexData of the IcoSphere.
  26089. */
  26090. VertexData.CreateIcoSphere = function (options) {
  26091. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26092. var radius = options.radius || 1;
  26093. var flat = (options.flat === undefined) ? true : options.flat;
  26094. var subdivisions = options.subdivisions || 4;
  26095. var radiusX = options.radiusX || radius;
  26096. var radiusY = options.radiusY || radius;
  26097. var radiusZ = options.radiusZ || radius;
  26098. var t = (1 + Math.sqrt(5)) / 2;
  26099. // 12 vertex x,y,z
  26100. var ico_vertices = [
  26101. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  26102. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  26103. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  26104. ];
  26105. // index of 3 vertex makes a face of icopshere
  26106. var ico_indices = [
  26107. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  26108. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  26109. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  26110. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  26111. ];
  26112. // vertex for uv have aliased position, not for UV
  26113. var vertices_unalias_id = [
  26114. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  26115. // vertex alias
  26116. 0,
  26117. 2,
  26118. 3,
  26119. 3,
  26120. 3,
  26121. 4,
  26122. 7,
  26123. 8,
  26124. 9,
  26125. 9,
  26126. 10,
  26127. 11 // 23: B + 12
  26128. ];
  26129. // uv as integer step (not pixels !)
  26130. var ico_vertexuv = [
  26131. 5, 1, 3, 1, 6, 4, 0, 0,
  26132. 5, 3, 4, 2, 2, 2, 4, 0,
  26133. 2, 0, 1, 1, 6, 0, 6, 2,
  26134. // vertex alias (for same vertex on different faces)
  26135. 0, 4,
  26136. 3, 3,
  26137. 4, 4,
  26138. 3, 1,
  26139. 4, 2,
  26140. 4, 4,
  26141. 0, 2,
  26142. 1, 1,
  26143. 2, 2,
  26144. 3, 3,
  26145. 1, 3,
  26146. 2, 4 // 23: B + 12
  26147. ];
  26148. // Vertices[0, 1, ...9, A, B] : position on UV plane
  26149. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  26150. // First island of uv mapping
  26151. // v = 4h 3+ 2
  26152. // v = 3h 9+ 4
  26153. // v = 2h 9+ 5 B
  26154. // v = 1h 9 1 0
  26155. // v = 0h 3 8 7 A
  26156. // u = 0 1 2 3 4 5 6 *a
  26157. // Second island of uv mapping
  26158. // v = 4h 0+ B+ 4+
  26159. // v = 3h A+ 2+
  26160. // v = 2h 7+ 6 3+
  26161. // v = 1h 8+ 3+
  26162. // v = 0h
  26163. // u = 0 1 2 3 4 5 6 *a
  26164. // Face layout on texture UV mapping
  26165. // ============
  26166. // \ 4 /\ 16 / ======
  26167. // \ / \ / /\ 11 /
  26168. // \/ 7 \/ / \ /
  26169. // ======= / 10 \/
  26170. // /\ 17 /\ =======
  26171. // / \ / \ \ 15 /\
  26172. // / 8 \/ 12 \ \ / \
  26173. // ============ \/ 6 \
  26174. // \ 18 /\ ============
  26175. // \ / \ \ 5 /\ 0 /
  26176. // \/ 13 \ \ / \ /
  26177. // ======= \/ 1 \/
  26178. // =============
  26179. // /\ 19 /\ 2 /\
  26180. // / \ / \ / \
  26181. // / 14 \/ 9 \/ 3 \
  26182. // ===================
  26183. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  26184. var ustep = 138 / 1024;
  26185. var vstep = 239 / 1024;
  26186. var uoffset = 60 / 1024;
  26187. var voffset = 26 / 1024;
  26188. // Second island should have margin, not to touch the first island
  26189. // avoid any borderline artefact in pixel rounding
  26190. var island_u_offset = -40 / 1024;
  26191. var island_v_offset = +20 / 1024;
  26192. // face is either island 0 or 1 :
  26193. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  26194. var island = [
  26195. 0, 0, 0, 0, 1,
  26196. 0, 0, 1, 1, 0,
  26197. 0, 0, 1, 1, 0,
  26198. 0, 1, 1, 1, 0 // 15 - 19
  26199. ];
  26200. var indices = [];
  26201. var positions = [];
  26202. var normals = [];
  26203. var uvs = [];
  26204. var current_indice = 0;
  26205. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  26206. var face_vertex_pos = new Array(3);
  26207. var face_vertex_uv = new Array(3);
  26208. var v012;
  26209. for (v012 = 0; v012 < 3; v012++) {
  26210. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  26211. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  26212. }
  26213. // create all with normals
  26214. for (var face = 0; face < 20; face++) {
  26215. // 3 vertex per face
  26216. for (v012 = 0; v012 < 3; v012++) {
  26217. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  26218. var v_id = ico_indices[3 * face + v012];
  26219. // vertex have 3D position (x,y,z)
  26220. 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]);
  26221. // Normalize to get normal, then scale to radius
  26222. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  26223. // uv Coordinates from vertex ID
  26224. 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);
  26225. }
  26226. // Subdivide the face (interpolate pos, norm, uv)
  26227. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  26228. // - norm is linear interpolation of vertex corner normal
  26229. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  26230. // - uv is linear interpolation
  26231. //
  26232. // Topology is as below for sub-divide by 2
  26233. // vertex shown as v0,v1,v2
  26234. // interp index is i1 to progress in range [v0,v1[
  26235. // interp index is i2 to progress in range [v0,v2[
  26236. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  26237. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  26238. //
  26239. //
  26240. // i2 v2
  26241. // ^ ^
  26242. // / / \
  26243. // / / \
  26244. // / / \
  26245. // / / (0,1) \
  26246. // / #---------\
  26247. // / / \ (0,0)'/ \
  26248. // / / \ / \
  26249. // / / \ / \
  26250. // / / (0,0) \ / (1,0) \
  26251. // / #---------#---------\
  26252. // v0 v1
  26253. //
  26254. // --------------------> i1
  26255. //
  26256. // interp of (i1,i2):
  26257. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  26258. // along i1 : lerp(x0,x1, i1/(S-i2))
  26259. //
  26260. // centroid of triangle is needed to get help normal computation
  26261. // (c1,c2) are used for centroid location
  26262. var interp_vertex = function (i1, i2, c1, c2) {
  26263. // vertex is interpolated from
  26264. // - face_vertex_pos[0..2]
  26265. // - face_vertex_uv[0..2]
  26266. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  26267. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  26268. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  26269. pos_interp.normalize();
  26270. var vertex_normal;
  26271. if (flat) {
  26272. // in flat mode, recalculate normal as face centroid normal
  26273. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  26274. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  26275. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  26276. }
  26277. else {
  26278. // in smooth mode, recalculate normal from each single vertex position
  26279. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  26280. }
  26281. // Vertex normal need correction due to X,Y,Z radius scaling
  26282. vertex_normal.x /= radiusX;
  26283. vertex_normal.y /= radiusY;
  26284. vertex_normal.z /= radiusZ;
  26285. vertex_normal.normalize();
  26286. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  26287. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  26288. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  26289. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  26290. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  26291. uvs.push(uv_interp.x, uv_interp.y);
  26292. // push each vertex has member of a face
  26293. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  26294. indices.push(current_indice);
  26295. current_indice++;
  26296. };
  26297. for (var i2 = 0; i2 < subdivisions; i2++) {
  26298. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  26299. // face : (i1,i2) for /\ :
  26300. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  26301. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26302. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26303. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26304. if (i1 + i2 + 1 < subdivisions) {
  26305. // face : (i1,i2)' for \/ :
  26306. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  26307. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26308. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26309. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26310. }
  26311. }
  26312. }
  26313. }
  26314. // Sides
  26315. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26316. // Result
  26317. var vertexData = new VertexData();
  26318. vertexData.indices = indices;
  26319. vertexData.positions = positions;
  26320. vertexData.normals = normals;
  26321. vertexData.uvs = uvs;
  26322. return vertexData;
  26323. };
  26324. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  26325. /**
  26326. * Creates the VertexData of the Polyhedron.
  26327. */
  26328. VertexData.CreatePolyhedron = function (options) {
  26329. // provided polyhedron types :
  26330. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  26331. // 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)
  26332. var polyhedra = [];
  26333. 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]] };
  26334. 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]] };
  26335. polyhedra[2] = {
  26336. 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]],
  26337. 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]]
  26338. };
  26339. polyhedra[3] = {
  26340. 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]],
  26341. 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]]
  26342. };
  26343. polyhedra[4] = {
  26344. 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]],
  26345. 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]]
  26346. };
  26347. 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]] };
  26348. 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]] };
  26349. 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]] };
  26350. 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]] };
  26351. 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]] };
  26352. 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]] };
  26353. 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]] };
  26354. 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]] };
  26355. 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]] };
  26356. polyhedra[14] = {
  26357. 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]],
  26358. 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]]
  26359. };
  26360. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  26361. var size = options.size;
  26362. var sizeX = options.sizeX || size || 1;
  26363. var sizeY = options.sizeY || size || 1;
  26364. var sizeZ = options.sizeZ || size || 1;
  26365. var data = options.custom || polyhedra[type];
  26366. var nbfaces = data.face.length;
  26367. var faceUV = options.faceUV || new Array(nbfaces);
  26368. var faceColors = options.faceColors;
  26369. var flat = (options.flat === undefined) ? true : options.flat;
  26370. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26371. var positions = [];
  26372. var indices = [];
  26373. var normals = [];
  26374. var uvs = [];
  26375. var colors = [];
  26376. var index = 0;
  26377. var faceIdx = 0; // face cursor in the array "indexes"
  26378. var indexes = [];
  26379. var i = 0;
  26380. var f = 0;
  26381. var u, v, ang, x, y, tmp;
  26382. // default face colors and UV if undefined
  26383. if (flat) {
  26384. for (f = 0; f < nbfaces; f++) {
  26385. if (faceColors && faceColors[f] === undefined) {
  26386. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26387. }
  26388. if (faceUV && faceUV[f] === undefined) {
  26389. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26390. }
  26391. }
  26392. }
  26393. if (!flat) {
  26394. for (i = 0; i < data.vertex.length; i++) {
  26395. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  26396. uvs.push(0, 0);
  26397. }
  26398. for (f = 0; f < nbfaces; f++) {
  26399. for (i = 0; i < data.face[f].length - 2; i++) {
  26400. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  26401. }
  26402. }
  26403. }
  26404. else {
  26405. for (f = 0; f < nbfaces; f++) {
  26406. var fl = data.face[f].length; // number of vertices of the current face
  26407. ang = 2 * Math.PI / fl;
  26408. x = 0.5 * Math.tan(ang / 2);
  26409. y = 0.5;
  26410. // positions, uvs, colors
  26411. for (i = 0; i < fl; i++) {
  26412. // positions
  26413. 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);
  26414. indexes.push(index);
  26415. index++;
  26416. // uvs
  26417. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  26418. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  26419. uvs.push(u, v);
  26420. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  26421. y = x * Math.sin(ang) + y * Math.cos(ang);
  26422. x = tmp;
  26423. // colors
  26424. if (faceColors) {
  26425. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  26426. }
  26427. }
  26428. // indices from indexes
  26429. for (i = 0; i < fl - 2; i++) {
  26430. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  26431. }
  26432. faceIdx += fl;
  26433. }
  26434. }
  26435. VertexData.ComputeNormals(positions, indices, normals);
  26436. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26437. var vertexData = new VertexData();
  26438. vertexData.positions = positions;
  26439. vertexData.indices = indices;
  26440. vertexData.normals = normals;
  26441. vertexData.uvs = uvs;
  26442. if (faceColors && flat) {
  26443. vertexData.colors = colors;
  26444. }
  26445. return vertexData;
  26446. };
  26447. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  26448. /**
  26449. * Creates the VertexData of the Torus Knot.
  26450. */
  26451. VertexData.CreateTorusKnot = function (options) {
  26452. var indices = [];
  26453. var positions = [];
  26454. var normals = [];
  26455. var uvs = [];
  26456. var radius = options.radius || 2;
  26457. var tube = options.tube || 0.5;
  26458. var radialSegments = options.radialSegments || 32;
  26459. var tubularSegments = options.tubularSegments || 32;
  26460. var p = options.p || 2;
  26461. var q = options.q || 3;
  26462. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26463. // Helper
  26464. var getPos = function (angle) {
  26465. var cu = Math.cos(angle);
  26466. var su = Math.sin(angle);
  26467. var quOverP = q / p * angle;
  26468. var cs = Math.cos(quOverP);
  26469. var tx = radius * (2 + cs) * 0.5 * cu;
  26470. var ty = radius * (2 + cs) * su * 0.5;
  26471. var tz = radius * Math.sin(quOverP) * 0.5;
  26472. return new BABYLON.Vector3(tx, ty, tz);
  26473. };
  26474. // Vertices
  26475. var i;
  26476. var j;
  26477. for (i = 0; i <= radialSegments; i++) {
  26478. var modI = i % radialSegments;
  26479. var u = modI / radialSegments * 2 * p * Math.PI;
  26480. var p1 = getPos(u);
  26481. var p2 = getPos(u + 0.01);
  26482. var tang = p2.subtract(p1);
  26483. var n = p2.add(p1);
  26484. var bitan = BABYLON.Vector3.Cross(tang, n);
  26485. n = BABYLON.Vector3.Cross(bitan, tang);
  26486. bitan.normalize();
  26487. n.normalize();
  26488. for (j = 0; j < tubularSegments; j++) {
  26489. var modJ = j % tubularSegments;
  26490. var v = modJ / tubularSegments * 2 * Math.PI;
  26491. var cx = -tube * Math.cos(v);
  26492. var cy = tube * Math.sin(v);
  26493. positions.push(p1.x + cx * n.x + cy * bitan.x);
  26494. positions.push(p1.y + cx * n.y + cy * bitan.y);
  26495. positions.push(p1.z + cx * n.z + cy * bitan.z);
  26496. uvs.push(i / radialSegments);
  26497. uvs.push(j / tubularSegments);
  26498. }
  26499. }
  26500. for (i = 0; i < radialSegments; i++) {
  26501. for (j = 0; j < tubularSegments; j++) {
  26502. var jNext = (j + 1) % tubularSegments;
  26503. var a = i * tubularSegments + j;
  26504. var b = (i + 1) * tubularSegments + j;
  26505. var c = (i + 1) * tubularSegments + jNext;
  26506. var d = i * tubularSegments + jNext;
  26507. indices.push(d);
  26508. indices.push(b);
  26509. indices.push(a);
  26510. indices.push(d);
  26511. indices.push(c);
  26512. indices.push(b);
  26513. }
  26514. }
  26515. // Normals
  26516. VertexData.ComputeNormals(positions, indices, normals);
  26517. // Sides
  26518. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26519. // Result
  26520. var vertexData = new VertexData();
  26521. vertexData.indices = indices;
  26522. vertexData.positions = positions;
  26523. vertexData.normals = normals;
  26524. vertexData.uvs = uvs;
  26525. return vertexData;
  26526. };
  26527. // Tools
  26528. /**
  26529. * @param {any} - positions (number[] or Float32Array)
  26530. * @param {any} - indices (number[] or Uint16Array)
  26531. * @param {any} - normals (number[] or Float32Array)
  26532. * options (optional) :
  26533. * facetPositions : optional array of facet positions (vector3)
  26534. * facetNormals : optional array of facet normals (vector3)
  26535. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  26536. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  26537. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  26538. * bbSize : optional bounding box size data, required for facetPartitioning computation
  26539. * bInfo : optional bounding info, required for facetPartitioning computation
  26540. */
  26541. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  26542. // temporary scalar variables
  26543. var index = 0; // facet index
  26544. var p1p2x = 0.0; // p1p2 vector x coordinate
  26545. var p1p2y = 0.0; // p1p2 vector y coordinate
  26546. var p1p2z = 0.0; // p1p2 vector z coordinate
  26547. var p3p2x = 0.0; // p3p2 vector x coordinate
  26548. var p3p2y = 0.0; // p3p2 vector y coordinate
  26549. var p3p2z = 0.0; // p3p2 vector z coordinate
  26550. var faceNormalx = 0.0; // facet normal x coordinate
  26551. var faceNormaly = 0.0; // facet normal y coordinate
  26552. var faceNormalz = 0.0; // facet normal z coordinate
  26553. var length = 0.0; // facet normal length before normalization
  26554. var v1x = 0; // vector1 x index in the positions array
  26555. var v1y = 0; // vector1 y index in the positions array
  26556. var v1z = 0; // vector1 z index in the positions array
  26557. var v2x = 0; // vector2 x index in the positions array
  26558. var v2y = 0; // vector2 y index in the positions array
  26559. var v2z = 0; // vector2 z index in the positions array
  26560. var v3x = 0; // vector3 x index in the positions array
  26561. var v3y = 0; // vector3 y index in the positions array
  26562. var v3z = 0; // vector3 z index in the positions array
  26563. var computeFacetNormals = false;
  26564. var computeFacetPositions = false;
  26565. var computeFacetPartitioning = false;
  26566. var faceNormalSign = 1;
  26567. if (options) {
  26568. computeFacetNormals = (options.facetNormals) ? true : false;
  26569. computeFacetPositions = (options.facetPositions) ? true : false;
  26570. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  26571. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  26572. }
  26573. // facetPartitioning reinit if needed
  26574. if (computeFacetPartitioning) {
  26575. var ox = 0; // X partitioning index for facet position
  26576. var oy = 0; // Y partinioning index for facet position
  26577. var oz = 0; // Z partinioning index for facet position
  26578. var b1x = 0; // X partitioning index for facet v1 vertex
  26579. var b1y = 0; // Y partitioning index for facet v1 vertex
  26580. var b1z = 0; // z partitioning index for facet v1 vertex
  26581. var b2x = 0; // X partitioning index for facet v2 vertex
  26582. var b2y = 0; // Y partitioning index for facet v2 vertex
  26583. var b2z = 0; // Z partitioning index for facet v2 vertex
  26584. var b3x = 0; // X partitioning index for facet v3 vertex
  26585. var b3y = 0; // Y partitioning index for facet v3 vertex
  26586. var b3z = 0; // Z partitioning index for facet v3 vertex
  26587. var block_idx_o = 0; // facet barycenter block index
  26588. var block_idx_v1 = 0; // v1 vertex block index
  26589. var block_idx_v2 = 0; // v2 vertex block index
  26590. var block_idx_v3 = 0; // v3 vertex block index
  26591. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  26592. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  26593. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  26594. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  26595. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  26596. var subSq = options.subDiv.max * options.subDiv.max;
  26597. options.facetPartitioning.length = 0;
  26598. }
  26599. // reset the normals
  26600. for (index = 0; index < positions.length; index++) {
  26601. normals[index] = 0.0;
  26602. }
  26603. // Loop : 1 indice triplet = 1 facet
  26604. var nbFaces = indices.length / 3;
  26605. for (index = 0; index < nbFaces; index++) {
  26606. // get the indexes of the coordinates of each vertex of the facet
  26607. v1x = indices[index * 3] * 3;
  26608. v1y = v1x + 1;
  26609. v1z = v1x + 2;
  26610. v2x = indices[index * 3 + 1] * 3;
  26611. v2y = v2x + 1;
  26612. v2z = v2x + 2;
  26613. v3x = indices[index * 3 + 2] * 3;
  26614. v3y = v3x + 1;
  26615. v3z = v3x + 2;
  26616. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  26617. p1p2y = positions[v1y] - positions[v2y];
  26618. p1p2z = positions[v1z] - positions[v2z];
  26619. p3p2x = positions[v3x] - positions[v2x];
  26620. p3p2y = positions[v3y] - positions[v2y];
  26621. p3p2z = positions[v3z] - positions[v2z];
  26622. // compute the face normal with the cross product
  26623. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  26624. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  26625. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  26626. // normalize this normal and store it in the array facetData
  26627. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26628. length = (length === 0) ? 1.0 : length;
  26629. faceNormalx /= length;
  26630. faceNormaly /= length;
  26631. faceNormalz /= length;
  26632. if (computeFacetNormals) {
  26633. options.facetNormals[index].x = faceNormalx;
  26634. options.facetNormals[index].y = faceNormaly;
  26635. options.facetNormals[index].z = faceNormalz;
  26636. }
  26637. if (computeFacetPositions) {
  26638. // compute and the facet barycenter coordinates in the array facetPositions
  26639. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  26640. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  26641. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  26642. }
  26643. if (computeFacetPartitioning) {
  26644. // store the facet indexes in arrays in the main facetPartitioning array :
  26645. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  26646. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26647. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26648. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26649. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26650. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26651. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26652. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26653. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26654. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26655. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26656. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26657. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26658. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  26659. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  26660. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  26661. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  26662. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  26663. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  26664. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  26665. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  26666. // push each facet index in each block containing the vertex
  26667. options.facetPartitioning[block_idx_v1].push(index);
  26668. if (block_idx_v2 != block_idx_v1) {
  26669. options.facetPartitioning[block_idx_v2].push(index);
  26670. }
  26671. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  26672. options.facetPartitioning[block_idx_v3].push(index);
  26673. }
  26674. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  26675. options.facetPartitioning[block_idx_o].push(index);
  26676. }
  26677. }
  26678. // compute the normals anyway
  26679. normals[v1x] += faceNormalx; // accumulate all the normals per face
  26680. normals[v1y] += faceNormaly;
  26681. normals[v1z] += faceNormalz;
  26682. normals[v2x] += faceNormalx;
  26683. normals[v2y] += faceNormaly;
  26684. normals[v2z] += faceNormalz;
  26685. normals[v3x] += faceNormalx;
  26686. normals[v3y] += faceNormaly;
  26687. normals[v3z] += faceNormalz;
  26688. }
  26689. // last normalization of each normal
  26690. for (index = 0; index < normals.length / 3; index++) {
  26691. faceNormalx = normals[index * 3];
  26692. faceNormaly = normals[index * 3 + 1];
  26693. faceNormalz = normals[index * 3 + 2];
  26694. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26695. length = (length === 0) ? 1.0 : length;
  26696. faceNormalx /= length;
  26697. faceNormaly /= length;
  26698. faceNormalz /= length;
  26699. normals[index * 3] = faceNormalx;
  26700. normals[index * 3 + 1] = faceNormaly;
  26701. normals[index * 3 + 2] = faceNormalz;
  26702. }
  26703. };
  26704. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  26705. var li = indices.length;
  26706. var ln = normals.length;
  26707. var i;
  26708. var n;
  26709. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26710. switch (sideOrientation) {
  26711. case BABYLON.Mesh.FRONTSIDE:
  26712. // nothing changed
  26713. break;
  26714. case BABYLON.Mesh.BACKSIDE:
  26715. var tmp;
  26716. // indices
  26717. for (i = 0; i < li; i += 3) {
  26718. tmp = indices[i];
  26719. indices[i] = indices[i + 2];
  26720. indices[i + 2] = tmp;
  26721. }
  26722. // normals
  26723. for (n = 0; n < ln; n++) {
  26724. normals[n] = -normals[n];
  26725. }
  26726. break;
  26727. case BABYLON.Mesh.DOUBLESIDE:
  26728. // positions
  26729. var lp = positions.length;
  26730. var l = lp / 3;
  26731. for (var p = 0; p < lp; p++) {
  26732. positions[lp + p] = positions[p];
  26733. }
  26734. // indices
  26735. for (i = 0; i < li; i += 3) {
  26736. indices[i + li] = indices[i + 2] + l;
  26737. indices[i + 1 + li] = indices[i + 1] + l;
  26738. indices[i + 2 + li] = indices[i] + l;
  26739. }
  26740. // normals
  26741. for (n = 0; n < ln; n++) {
  26742. normals[ln + n] = -normals[n];
  26743. }
  26744. // uvs
  26745. var lu = uvs.length;
  26746. var u = 0;
  26747. for (u = 0; u < lu; u++) {
  26748. uvs[u + lu] = uvs[u];
  26749. }
  26750. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  26751. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  26752. u = 0;
  26753. for (i = 0; i < lu / 2; i++) {
  26754. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  26755. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  26756. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  26757. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  26758. u += 2;
  26759. }
  26760. break;
  26761. }
  26762. };
  26763. /**
  26764. * Creates a new VertexData from the imported parameters.
  26765. */
  26766. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  26767. var vertexData = new VertexData();
  26768. // positions
  26769. var positions = parsedVertexData.positions;
  26770. if (positions) {
  26771. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  26772. }
  26773. // normals
  26774. var normals = parsedVertexData.normals;
  26775. if (normals) {
  26776. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  26777. }
  26778. // tangents
  26779. var tangents = parsedVertexData.tangents;
  26780. if (tangents) {
  26781. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  26782. }
  26783. // uvs
  26784. var uvs = parsedVertexData.uvs;
  26785. if (uvs) {
  26786. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  26787. }
  26788. // uv2s
  26789. var uv2s = parsedVertexData.uv2s;
  26790. if (uv2s) {
  26791. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  26792. }
  26793. // uv3s
  26794. var uv3s = parsedVertexData.uv3s;
  26795. if (uv3s) {
  26796. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  26797. }
  26798. // uv4s
  26799. var uv4s = parsedVertexData.uv4s;
  26800. if (uv4s) {
  26801. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  26802. }
  26803. // uv5s
  26804. var uv5s = parsedVertexData.uv5s;
  26805. if (uv5s) {
  26806. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  26807. }
  26808. // uv6s
  26809. var uv6s = parsedVertexData.uv6s;
  26810. if (uv6s) {
  26811. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  26812. }
  26813. // colors
  26814. var colors = parsedVertexData.colors;
  26815. if (colors) {
  26816. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  26817. }
  26818. // matricesIndices
  26819. var matricesIndices = parsedVertexData.matricesIndices;
  26820. if (matricesIndices) {
  26821. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  26822. }
  26823. // matricesWeights
  26824. var matricesWeights = parsedVertexData.matricesWeights;
  26825. if (matricesWeights) {
  26826. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  26827. }
  26828. // indices
  26829. var indices = parsedVertexData.indices;
  26830. if (indices) {
  26831. vertexData.indices = indices;
  26832. }
  26833. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  26834. };
  26835. return VertexData;
  26836. }());
  26837. BABYLON.VertexData = VertexData;
  26838. })(BABYLON || (BABYLON = {}));
  26839. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  26840. var BABYLON;
  26841. (function (BABYLON) {
  26842. var Geometry = (function () {
  26843. function Geometry(id, scene, vertexData, updatable, mesh) {
  26844. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26845. this._totalVertices = 0;
  26846. this._isDisposed = false;
  26847. this.id = id;
  26848. this._engine = scene.getEngine();
  26849. this._meshes = [];
  26850. this._scene = scene;
  26851. //Init vertex buffer cache
  26852. this._vertexBuffers = {};
  26853. this._indices = [];
  26854. // vertexData
  26855. if (vertexData) {
  26856. this.setAllVerticesData(vertexData, updatable);
  26857. }
  26858. else {
  26859. this._totalVertices = 0;
  26860. this._indices = [];
  26861. }
  26862. if (this._engine.getCaps().vertexArrayObject) {
  26863. this._vertexArrayObjects = {};
  26864. }
  26865. // applyToMesh
  26866. if (mesh) {
  26867. if (mesh.getClassName() === "LinesMesh") {
  26868. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  26869. this.updateExtend();
  26870. }
  26871. this.applyToMesh(mesh);
  26872. mesh.computeWorldMatrix(true);
  26873. }
  26874. }
  26875. Object.defineProperty(Geometry.prototype, "boundingBias", {
  26876. /**
  26877. * 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
  26878. * @returns The Bias Vector
  26879. */
  26880. get: function () {
  26881. return this._boundingBias;
  26882. },
  26883. set: function (value) {
  26884. if (this._boundingBias && this._boundingBias.equals(value)) {
  26885. return;
  26886. }
  26887. this._boundingBias = value.clone();
  26888. this.updateBoundingInfo(true, null);
  26889. },
  26890. enumerable: true,
  26891. configurable: true
  26892. });
  26893. Object.defineProperty(Geometry.prototype, "extend", {
  26894. get: function () {
  26895. return this._extend;
  26896. },
  26897. enumerable: true,
  26898. configurable: true
  26899. });
  26900. Geometry.prototype.getScene = function () {
  26901. return this._scene;
  26902. };
  26903. Geometry.prototype.getEngine = function () {
  26904. return this._engine;
  26905. };
  26906. Geometry.prototype.isReady = function () {
  26907. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  26908. };
  26909. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  26910. get: function () {
  26911. for (var index = 0; index < this._meshes.length; index++) {
  26912. if (!this._meshes[index].doNotSerialize) {
  26913. return false;
  26914. }
  26915. }
  26916. return true;
  26917. },
  26918. enumerable: true,
  26919. configurable: true
  26920. });
  26921. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  26922. vertexData.applyToGeometry(this, updatable);
  26923. this.notifyUpdate();
  26924. };
  26925. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26926. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  26927. this.setVerticesBuffer(buffer);
  26928. };
  26929. Geometry.prototype.removeVerticesData = function (kind) {
  26930. if (this._vertexBuffers[kind]) {
  26931. this._vertexBuffers[kind].dispose();
  26932. delete this._vertexBuffers[kind];
  26933. }
  26934. };
  26935. Geometry.prototype.setVerticesBuffer = function (buffer) {
  26936. var kind = buffer.getKind();
  26937. if (this._vertexBuffers[kind]) {
  26938. this._vertexBuffers[kind].dispose();
  26939. }
  26940. this._vertexBuffers[kind] = buffer;
  26941. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26942. var data = buffer.getData();
  26943. var stride = buffer.getStrideSize();
  26944. this._totalVertices = data.length / stride;
  26945. this.updateExtend(data, stride);
  26946. this._resetPointsArrayCache();
  26947. var meshes = this._meshes;
  26948. var numOfMeshes = meshes.length;
  26949. for (var index = 0; index < numOfMeshes; index++) {
  26950. var mesh = meshes[index];
  26951. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26952. mesh._createGlobalSubMesh();
  26953. mesh.computeWorldMatrix(true);
  26954. }
  26955. }
  26956. this.notifyUpdate(kind);
  26957. if (this._vertexArrayObjects) {
  26958. this._disposeVertexArrayObjects();
  26959. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  26960. }
  26961. };
  26962. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  26963. var vertexBuffer = this.getVertexBuffer(kind);
  26964. if (!vertexBuffer) {
  26965. return;
  26966. }
  26967. vertexBuffer.updateDirectly(data, offset);
  26968. this.notifyUpdate(kind);
  26969. };
  26970. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  26971. var vertexBuffer = this.getVertexBuffer(kind);
  26972. if (!vertexBuffer) {
  26973. return;
  26974. }
  26975. vertexBuffer.update(data);
  26976. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26977. var stride = vertexBuffer.getStrideSize();
  26978. this._totalVertices = data.length / stride;
  26979. this.updateBoundingInfo(updateExtends, data);
  26980. }
  26981. this.notifyUpdate(kind);
  26982. };
  26983. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  26984. if (updateExtends) {
  26985. this.updateExtend(data);
  26986. }
  26987. var meshes = this._meshes;
  26988. var numOfMeshes = meshes.length;
  26989. this._resetPointsArrayCache();
  26990. for (var index = 0; index < numOfMeshes; index++) {
  26991. var mesh = meshes[index];
  26992. if (updateExtends) {
  26993. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26994. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  26995. var subMesh = mesh.subMeshes[subIndex];
  26996. subMesh.refreshBoundingInfo();
  26997. }
  26998. }
  26999. }
  27000. };
  27001. Geometry.prototype._bind = function (effect, indexToBind) {
  27002. if (indexToBind === void 0) { indexToBind = undefined; }
  27003. if (indexToBind === undefined) {
  27004. indexToBind = this._indexBuffer;
  27005. }
  27006. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  27007. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  27008. return;
  27009. }
  27010. // Using VAO
  27011. if (!this._vertexArrayObjects[effect.key]) {
  27012. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  27013. }
  27014. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  27015. };
  27016. Geometry.prototype.getTotalVertices = function () {
  27017. if (!this.isReady()) {
  27018. return 0;
  27019. }
  27020. return this._totalVertices;
  27021. };
  27022. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27023. var vertexBuffer = this.getVertexBuffer(kind);
  27024. if (!vertexBuffer) {
  27025. return null;
  27026. }
  27027. var orig = vertexBuffer.getData();
  27028. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  27029. return orig;
  27030. }
  27031. else {
  27032. var len = orig.length;
  27033. var copy = [];
  27034. for (var i = 0; i < len; i++) {
  27035. copy.push(orig[i]);
  27036. }
  27037. return copy;
  27038. }
  27039. };
  27040. Geometry.prototype.getVertexBuffer = function (kind) {
  27041. if (!this.isReady()) {
  27042. return null;
  27043. }
  27044. return this._vertexBuffers[kind];
  27045. };
  27046. Geometry.prototype.getVertexBuffers = function () {
  27047. if (!this.isReady()) {
  27048. return null;
  27049. }
  27050. return this._vertexBuffers;
  27051. };
  27052. Geometry.prototype.isVerticesDataPresent = function (kind) {
  27053. if (!this._vertexBuffers) {
  27054. if (this._delayInfo) {
  27055. return this._delayInfo.indexOf(kind) !== -1;
  27056. }
  27057. return false;
  27058. }
  27059. return this._vertexBuffers[kind] !== undefined;
  27060. };
  27061. Geometry.prototype.getVerticesDataKinds = function () {
  27062. var result = [];
  27063. var kind;
  27064. if (!this._vertexBuffers && this._delayInfo) {
  27065. for (kind in this._delayInfo) {
  27066. result.push(kind);
  27067. }
  27068. }
  27069. else {
  27070. for (kind in this._vertexBuffers) {
  27071. result.push(kind);
  27072. }
  27073. }
  27074. return result;
  27075. };
  27076. Geometry.prototype.setIndices = function (indices, totalVertices) {
  27077. if (this._indexBuffer) {
  27078. this._engine._releaseBuffer(this._indexBuffer);
  27079. }
  27080. this._disposeVertexArrayObjects();
  27081. this._indices = indices;
  27082. if (this._meshes.length !== 0 && this._indices) {
  27083. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27084. }
  27085. if (totalVertices !== undefined) {
  27086. this._totalVertices = totalVertices;
  27087. }
  27088. var meshes = this._meshes;
  27089. var numOfMeshes = meshes.length;
  27090. for (var index = 0; index < numOfMeshes; index++) {
  27091. meshes[index]._createGlobalSubMesh();
  27092. }
  27093. this.notifyUpdate();
  27094. };
  27095. Geometry.prototype.getTotalIndices = function () {
  27096. if (!this.isReady()) {
  27097. return 0;
  27098. }
  27099. return this._indices.length;
  27100. };
  27101. Geometry.prototype.getIndices = function (copyWhenShared) {
  27102. if (!this.isReady()) {
  27103. return null;
  27104. }
  27105. var orig = this._indices;
  27106. if (!copyWhenShared || this._meshes.length === 1) {
  27107. return orig;
  27108. }
  27109. else {
  27110. var len = orig.length;
  27111. var copy = [];
  27112. for (var i = 0; i < len; i++) {
  27113. copy.push(orig[i]);
  27114. }
  27115. return copy;
  27116. }
  27117. };
  27118. Geometry.prototype.getIndexBuffer = function () {
  27119. if (!this.isReady()) {
  27120. return null;
  27121. }
  27122. return this._indexBuffer;
  27123. };
  27124. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  27125. if (!effect || !this._vertexArrayObjects) {
  27126. return;
  27127. }
  27128. if (this._vertexArrayObjects[effect.key]) {
  27129. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  27130. delete this._vertexArrayObjects[effect.key];
  27131. }
  27132. };
  27133. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  27134. var meshes = this._meshes;
  27135. var index = meshes.indexOf(mesh);
  27136. if (index === -1) {
  27137. return;
  27138. }
  27139. meshes.splice(index, 1);
  27140. mesh._geometry = null;
  27141. if (meshes.length === 0 && shouldDispose) {
  27142. this.dispose();
  27143. }
  27144. };
  27145. Geometry.prototype.applyToMesh = function (mesh) {
  27146. if (mesh._geometry === this) {
  27147. return;
  27148. }
  27149. var previousGeometry = mesh._geometry;
  27150. if (previousGeometry) {
  27151. previousGeometry.releaseForMesh(mesh);
  27152. }
  27153. var meshes = this._meshes;
  27154. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  27155. mesh._geometry = this;
  27156. this._scene.pushGeometry(this);
  27157. meshes.push(mesh);
  27158. if (this.isReady()) {
  27159. this._applyToMesh(mesh);
  27160. }
  27161. else {
  27162. mesh._boundingInfo = this._boundingInfo;
  27163. }
  27164. };
  27165. Geometry.prototype.updateExtend = function (data, stride) {
  27166. if (data === void 0) { data = null; }
  27167. if (!data) {
  27168. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  27169. }
  27170. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  27171. };
  27172. Geometry.prototype._applyToMesh = function (mesh) {
  27173. var numOfMeshes = this._meshes.length;
  27174. // vertexBuffers
  27175. for (var kind in this._vertexBuffers) {
  27176. if (numOfMeshes === 1) {
  27177. this._vertexBuffers[kind].create();
  27178. }
  27179. var buffer = this._vertexBuffers[kind].getBuffer();
  27180. if (buffer)
  27181. buffer.references = numOfMeshes;
  27182. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27183. if (!this._extend) {
  27184. this.updateExtend(this._vertexBuffers[kind].getData());
  27185. }
  27186. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27187. mesh._createGlobalSubMesh();
  27188. //bounding info was just created again, world matrix should be applied again.
  27189. mesh._updateBoundingInfo();
  27190. }
  27191. }
  27192. // indexBuffer
  27193. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  27194. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27195. }
  27196. if (this._indexBuffer) {
  27197. this._indexBuffer.references = numOfMeshes;
  27198. }
  27199. };
  27200. Geometry.prototype.notifyUpdate = function (kind) {
  27201. if (this.onGeometryUpdated) {
  27202. this.onGeometryUpdated(this, kind);
  27203. }
  27204. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  27205. var mesh = _a[_i];
  27206. mesh._markSubMeshesAsAttributesDirty();
  27207. }
  27208. };
  27209. Geometry.prototype.load = function (scene, onLoaded) {
  27210. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27211. return;
  27212. }
  27213. if (this.isReady()) {
  27214. if (onLoaded) {
  27215. onLoaded();
  27216. }
  27217. return;
  27218. }
  27219. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27220. this._queueLoad(scene, onLoaded);
  27221. };
  27222. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  27223. var _this = this;
  27224. scene._addPendingData(this);
  27225. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27226. _this._delayLoadingFunction(JSON.parse(data), _this);
  27227. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27228. _this._delayInfo = [];
  27229. scene._removePendingData(_this);
  27230. var meshes = _this._meshes;
  27231. var numOfMeshes = meshes.length;
  27232. for (var index = 0; index < numOfMeshes; index++) {
  27233. _this._applyToMesh(meshes[index]);
  27234. }
  27235. if (onLoaded) {
  27236. onLoaded();
  27237. }
  27238. }, function () { }, scene.database);
  27239. };
  27240. /**
  27241. * Invert the geometry to move from a right handed system to a left handed one.
  27242. */
  27243. Geometry.prototype.toLeftHanded = function () {
  27244. // Flip faces
  27245. var tIndices = this.getIndices(false);
  27246. if (tIndices != null && tIndices.length > 0) {
  27247. for (var i = 0; i < tIndices.length; i += 3) {
  27248. var tTemp = tIndices[i + 0];
  27249. tIndices[i + 0] = tIndices[i + 2];
  27250. tIndices[i + 2] = tTemp;
  27251. }
  27252. this.setIndices(tIndices);
  27253. }
  27254. // Negate position.z
  27255. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  27256. if (tPositions != null && tPositions.length > 0) {
  27257. for (var i = 0; i < tPositions.length; i += 3) {
  27258. tPositions[i + 2] = -tPositions[i + 2];
  27259. }
  27260. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  27261. }
  27262. // Negate normal.z
  27263. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  27264. if (tNormals != null && tNormals.length > 0) {
  27265. for (var i = 0; i < tNormals.length; i += 3) {
  27266. tNormals[i + 2] = -tNormals[i + 2];
  27267. }
  27268. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  27269. }
  27270. };
  27271. // Cache
  27272. Geometry.prototype._resetPointsArrayCache = function () {
  27273. this._positions = null;
  27274. };
  27275. Geometry.prototype._generatePointsArray = function () {
  27276. if (this._positions)
  27277. return true;
  27278. this._positions = [];
  27279. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27280. if (!data) {
  27281. return false;
  27282. }
  27283. for (var index = 0; index < data.length; index += 3) {
  27284. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  27285. }
  27286. return true;
  27287. };
  27288. Geometry.prototype.isDisposed = function () {
  27289. return this._isDisposed;
  27290. };
  27291. Geometry.prototype._disposeVertexArrayObjects = function () {
  27292. if (this._vertexArrayObjects) {
  27293. for (var kind in this._vertexArrayObjects) {
  27294. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  27295. }
  27296. this._vertexArrayObjects = {};
  27297. }
  27298. };
  27299. Geometry.prototype.dispose = function () {
  27300. var meshes = this._meshes;
  27301. var numOfMeshes = meshes.length;
  27302. var index;
  27303. for (index = 0; index < numOfMeshes; index++) {
  27304. this.releaseForMesh(meshes[index]);
  27305. }
  27306. this._meshes = [];
  27307. this._disposeVertexArrayObjects();
  27308. for (var kind in this._vertexBuffers) {
  27309. this._vertexBuffers[kind].dispose();
  27310. }
  27311. this._vertexBuffers = {};
  27312. this._totalVertices = 0;
  27313. if (this._indexBuffer) {
  27314. this._engine._releaseBuffer(this._indexBuffer);
  27315. }
  27316. this._indexBuffer = null;
  27317. this._indices = [];
  27318. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27319. this.delayLoadingFile = null;
  27320. this._delayLoadingFunction = null;
  27321. this._delayInfo = [];
  27322. this._boundingInfo = null;
  27323. this._scene.removeGeometry(this);
  27324. this._isDisposed = true;
  27325. };
  27326. Geometry.prototype.copy = function (id) {
  27327. var vertexData = new BABYLON.VertexData();
  27328. vertexData.indices = [];
  27329. var indices = this.getIndices();
  27330. for (var index = 0; index < indices.length; index++) {
  27331. vertexData.indices.push(indices[index]);
  27332. }
  27333. var updatable = false;
  27334. var stopChecking = false;
  27335. var kind;
  27336. for (kind in this._vertexBuffers) {
  27337. // using slice() to make a copy of the array and not just reference it
  27338. var data = this.getVerticesData(kind);
  27339. if (data instanceof Float32Array) {
  27340. vertexData.set(new Float32Array(data), kind);
  27341. }
  27342. else {
  27343. vertexData.set(data.slice(0), kind);
  27344. }
  27345. if (!stopChecking) {
  27346. updatable = this.getVertexBuffer(kind).isUpdatable();
  27347. stopChecking = !updatable;
  27348. }
  27349. }
  27350. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  27351. geometry.delayLoadState = this.delayLoadState;
  27352. geometry.delayLoadingFile = this.delayLoadingFile;
  27353. geometry._delayLoadingFunction = this._delayLoadingFunction;
  27354. for (kind in this._delayInfo) {
  27355. geometry._delayInfo = geometry._delayInfo || [];
  27356. geometry._delayInfo.push(kind);
  27357. }
  27358. // Bounding info
  27359. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27360. return geometry;
  27361. };
  27362. Geometry.prototype.serialize = function () {
  27363. var serializationObject = {};
  27364. serializationObject.id = this.id;
  27365. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  27366. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27367. }
  27368. return serializationObject;
  27369. };
  27370. Geometry.prototype.toNumberArray = function (origin) {
  27371. if (Array.isArray(origin)) {
  27372. return origin;
  27373. }
  27374. else {
  27375. return Array.prototype.slice.call(origin);
  27376. }
  27377. };
  27378. Geometry.prototype.serializeVerticeData = function () {
  27379. var serializationObject = this.serialize();
  27380. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27381. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  27382. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  27383. serializationObject.positions._updatable = true;
  27384. }
  27385. }
  27386. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27387. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  27388. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  27389. serializationObject.normals._updatable = true;
  27390. }
  27391. }
  27392. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27393. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  27394. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  27395. serializationObject.uvs._updatable = true;
  27396. }
  27397. }
  27398. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27399. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  27400. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  27401. serializationObject.uv2s._updatable = true;
  27402. }
  27403. }
  27404. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27405. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  27406. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  27407. serializationObject.uv3s._updatable = true;
  27408. }
  27409. }
  27410. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27411. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  27412. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  27413. serializationObject.uv4s._updatable = true;
  27414. }
  27415. }
  27416. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27417. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  27418. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  27419. serializationObject.uv5s._updatable = true;
  27420. }
  27421. }
  27422. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27423. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  27424. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  27425. serializationObject.uv6s._updatable = true;
  27426. }
  27427. }
  27428. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27429. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  27430. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  27431. serializationObject.colors._updatable = true;
  27432. }
  27433. }
  27434. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27435. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  27436. serializationObject.matricesIndices._isExpanded = true;
  27437. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  27438. serializationObject.matricesIndices._updatable = true;
  27439. }
  27440. }
  27441. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27442. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  27443. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  27444. serializationObject.matricesWeights._updatable = true;
  27445. }
  27446. }
  27447. serializationObject.indices = this.toNumberArray(this.getIndices());
  27448. return serializationObject;
  27449. };
  27450. // Statics
  27451. Geometry.ExtractFromMesh = function (mesh, id) {
  27452. var geometry = mesh._geometry;
  27453. if (!geometry) {
  27454. return null;
  27455. }
  27456. return geometry.copy(id);
  27457. };
  27458. /**
  27459. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  27460. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  27461. * Be aware Math.random() could cause collisions, but:
  27462. * "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"
  27463. */
  27464. Geometry.RandomId = function () {
  27465. return BABYLON.Tools.RandomId();
  27466. };
  27467. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  27468. var scene = mesh.getScene();
  27469. // Geometry
  27470. var geometryId = parsedGeometry.geometryId;
  27471. if (geometryId) {
  27472. var geometry = scene.getGeometryByID(geometryId);
  27473. if (geometry) {
  27474. geometry.applyToMesh(mesh);
  27475. }
  27476. }
  27477. else if (parsedGeometry instanceof ArrayBuffer) {
  27478. var binaryInfo = mesh._binaryInfo;
  27479. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  27480. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  27481. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  27482. }
  27483. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  27484. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  27485. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  27486. }
  27487. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  27488. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  27489. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  27490. }
  27491. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  27492. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  27493. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  27494. }
  27495. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  27496. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  27497. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  27498. }
  27499. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  27500. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  27501. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  27502. }
  27503. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  27504. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  27505. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  27506. }
  27507. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  27508. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  27509. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  27510. }
  27511. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  27512. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  27513. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  27514. }
  27515. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  27516. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  27517. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  27518. }
  27519. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  27520. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  27521. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  27522. }
  27523. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  27524. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  27525. mesh.setIndices(indicesData);
  27526. }
  27527. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  27528. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  27529. mesh.subMeshes = [];
  27530. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  27531. var materialIndex = subMeshesData[(i * 5) + 0];
  27532. var verticesStart = subMeshesData[(i * 5) + 1];
  27533. var verticesCount = subMeshesData[(i * 5) + 2];
  27534. var indexStart = subMeshesData[(i * 5) + 3];
  27535. var indexCount = subMeshesData[(i * 5) + 4];
  27536. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  27537. }
  27538. }
  27539. }
  27540. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  27541. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  27542. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  27543. if (parsedGeometry.uvs) {
  27544. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  27545. }
  27546. if (parsedGeometry.uvs2) {
  27547. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  27548. }
  27549. if (parsedGeometry.uvs3) {
  27550. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  27551. }
  27552. if (parsedGeometry.uvs4) {
  27553. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  27554. }
  27555. if (parsedGeometry.uvs5) {
  27556. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  27557. }
  27558. if (parsedGeometry.uvs6) {
  27559. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  27560. }
  27561. if (parsedGeometry.colors) {
  27562. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  27563. }
  27564. if (parsedGeometry.matricesIndices) {
  27565. if (!parsedGeometry.matricesIndices._isExpanded) {
  27566. var floatIndices = [];
  27567. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  27568. var matricesIndex = parsedGeometry.matricesIndices[i];
  27569. floatIndices.push(matricesIndex & 0x000000FF);
  27570. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27571. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27572. floatIndices.push(matricesIndex >> 24);
  27573. }
  27574. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  27575. }
  27576. else {
  27577. delete parsedGeometry.matricesIndices._isExpanded;
  27578. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  27579. }
  27580. }
  27581. if (parsedGeometry.matricesIndicesExtra) {
  27582. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  27583. var floatIndices = [];
  27584. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  27585. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  27586. floatIndices.push(matricesIndex & 0x000000FF);
  27587. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27588. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27589. floatIndices.push(matricesIndex >> 24);
  27590. }
  27591. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  27592. }
  27593. else {
  27594. delete parsedGeometry.matricesIndices._isExpanded;
  27595. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  27596. }
  27597. }
  27598. if (parsedGeometry.matricesWeights) {
  27599. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  27600. }
  27601. if (parsedGeometry.matricesWeightsExtra) {
  27602. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  27603. }
  27604. mesh.setIndices(parsedGeometry.indices);
  27605. }
  27606. // SubMeshes
  27607. if (parsedGeometry.subMeshes) {
  27608. mesh.subMeshes = [];
  27609. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  27610. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  27611. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  27612. }
  27613. }
  27614. // Flat shading
  27615. if (mesh._shouldGenerateFlatShading) {
  27616. mesh.convertToFlatShadedMesh();
  27617. delete mesh._shouldGenerateFlatShading;
  27618. }
  27619. // Update
  27620. mesh.computeWorldMatrix(true);
  27621. // Octree
  27622. if (scene['_selectionOctree']) {
  27623. scene['_selectionOctree'].addMesh(mesh);
  27624. }
  27625. };
  27626. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  27627. if (scene.getGeometryByID(parsedVertexData.id)) {
  27628. return null; // null since geometry could be something else than a box...
  27629. }
  27630. var geometry = new Geometry(parsedVertexData.id, scene);
  27631. if (BABYLON.Tags) {
  27632. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  27633. }
  27634. if (parsedVertexData.delayLoadingFile) {
  27635. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27636. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  27637. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  27638. geometry._delayInfo = [];
  27639. if (parsedVertexData.hasUVs) {
  27640. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27641. }
  27642. if (parsedVertexData.hasUVs2) {
  27643. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27644. }
  27645. if (parsedVertexData.hasUVs3) {
  27646. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27647. }
  27648. if (parsedVertexData.hasUVs4) {
  27649. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27650. }
  27651. if (parsedVertexData.hasUVs5) {
  27652. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  27653. }
  27654. if (parsedVertexData.hasUVs6) {
  27655. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  27656. }
  27657. if (parsedVertexData.hasColors) {
  27658. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27659. }
  27660. if (parsedVertexData.hasMatricesIndices) {
  27661. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27662. }
  27663. if (parsedVertexData.hasMatricesWeights) {
  27664. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27665. }
  27666. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  27667. }
  27668. else {
  27669. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  27670. }
  27671. scene.pushGeometry(geometry, true);
  27672. return geometry;
  27673. };
  27674. return Geometry;
  27675. }());
  27676. BABYLON.Geometry = Geometry;
  27677. /////// Primitives //////////////////////////////////////////////
  27678. (function (Geometry) {
  27679. var Primitives;
  27680. (function (Primitives) {
  27681. /// Abstract class
  27682. var _Primitive = (function (_super) {
  27683. __extends(_Primitive, _super);
  27684. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  27685. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  27686. _this._canBeRegenerated = _canBeRegenerated;
  27687. _this._beingRegenerated = true;
  27688. _this.regenerate();
  27689. _this._beingRegenerated = false;
  27690. return _this;
  27691. }
  27692. _Primitive.prototype.canBeRegenerated = function () {
  27693. return this._canBeRegenerated;
  27694. };
  27695. _Primitive.prototype.regenerate = function () {
  27696. if (!this._canBeRegenerated) {
  27697. return;
  27698. }
  27699. this._beingRegenerated = true;
  27700. this.setAllVerticesData(this._regenerateVertexData(), false);
  27701. this._beingRegenerated = false;
  27702. };
  27703. _Primitive.prototype.asNewGeometry = function (id) {
  27704. return _super.prototype.copy.call(this, id);
  27705. };
  27706. // overrides
  27707. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  27708. if (!this._beingRegenerated) {
  27709. return;
  27710. }
  27711. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  27712. };
  27713. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  27714. if (!this._beingRegenerated) {
  27715. return;
  27716. }
  27717. _super.prototype.setVerticesData.call(this, kind, data, false);
  27718. };
  27719. // to override
  27720. // protected
  27721. _Primitive.prototype._regenerateVertexData = function () {
  27722. throw new Error("Abstract method");
  27723. };
  27724. _Primitive.prototype.copy = function (id) {
  27725. throw new Error("Must be overriden in sub-classes.");
  27726. };
  27727. _Primitive.prototype.serialize = function () {
  27728. var serializationObject = _super.prototype.serialize.call(this);
  27729. serializationObject.canBeRegenerated = this.canBeRegenerated();
  27730. return serializationObject;
  27731. };
  27732. return _Primitive;
  27733. }(Geometry));
  27734. Primitives._Primitive = _Primitive;
  27735. var Ribbon = (function (_super) {
  27736. __extends(Ribbon, _super);
  27737. // Members
  27738. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  27739. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27740. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27741. _this.pathArray = pathArray;
  27742. _this.closeArray = closeArray;
  27743. _this.closePath = closePath;
  27744. _this.offset = offset;
  27745. _this.side = side;
  27746. return _this;
  27747. }
  27748. Ribbon.prototype._regenerateVertexData = function () {
  27749. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  27750. };
  27751. Ribbon.prototype.copy = function (id) {
  27752. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  27753. };
  27754. return Ribbon;
  27755. }(_Primitive));
  27756. Primitives.Ribbon = Ribbon;
  27757. var Box = (function (_super) {
  27758. __extends(Box, _super);
  27759. // Members
  27760. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  27761. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27762. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27763. _this.size = size;
  27764. _this.side = side;
  27765. return _this;
  27766. }
  27767. Box.prototype._regenerateVertexData = function () {
  27768. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  27769. };
  27770. Box.prototype.copy = function (id) {
  27771. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27772. };
  27773. Box.prototype.serialize = function () {
  27774. var serializationObject = _super.prototype.serialize.call(this);
  27775. serializationObject.size = this.size;
  27776. return serializationObject;
  27777. };
  27778. Box.Parse = function (parsedBox, scene) {
  27779. if (scene.getGeometryByID(parsedBox.id)) {
  27780. return null; // null since geometry could be something else than a box...
  27781. }
  27782. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  27783. if (BABYLON.Tags) {
  27784. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  27785. }
  27786. scene.pushGeometry(box, true);
  27787. return box;
  27788. };
  27789. return Box;
  27790. }(_Primitive));
  27791. Primitives.Box = Box;
  27792. var Sphere = (function (_super) {
  27793. __extends(Sphere, _super);
  27794. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  27795. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27796. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27797. _this.segments = segments;
  27798. _this.diameter = diameter;
  27799. _this.side = side;
  27800. return _this;
  27801. }
  27802. Sphere.prototype._regenerateVertexData = function () {
  27803. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  27804. };
  27805. Sphere.prototype.copy = function (id) {
  27806. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  27807. };
  27808. Sphere.prototype.serialize = function () {
  27809. var serializationObject = _super.prototype.serialize.call(this);
  27810. serializationObject.segments = this.segments;
  27811. serializationObject.diameter = this.diameter;
  27812. return serializationObject;
  27813. };
  27814. Sphere.Parse = function (parsedSphere, scene) {
  27815. if (scene.getGeometryByID(parsedSphere.id)) {
  27816. return null; // null since geometry could be something else than a sphere...
  27817. }
  27818. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  27819. if (BABYLON.Tags) {
  27820. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  27821. }
  27822. scene.pushGeometry(sphere, true);
  27823. return sphere;
  27824. };
  27825. return Sphere;
  27826. }(_Primitive));
  27827. Primitives.Sphere = Sphere;
  27828. var Disc = (function (_super) {
  27829. __extends(Disc, _super);
  27830. // Members
  27831. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  27832. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27833. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27834. _this.radius = radius;
  27835. _this.tessellation = tessellation;
  27836. _this.side = side;
  27837. return _this;
  27838. }
  27839. Disc.prototype._regenerateVertexData = function () {
  27840. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  27841. };
  27842. Disc.prototype.copy = function (id) {
  27843. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  27844. };
  27845. return Disc;
  27846. }(_Primitive));
  27847. Primitives.Disc = Disc;
  27848. var Cylinder = (function (_super) {
  27849. __extends(Cylinder, _super);
  27850. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  27851. if (subdivisions === void 0) { subdivisions = 1; }
  27852. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27853. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27854. _this.height = height;
  27855. _this.diameterTop = diameterTop;
  27856. _this.diameterBottom = diameterBottom;
  27857. _this.tessellation = tessellation;
  27858. _this.subdivisions = subdivisions;
  27859. _this.side = side;
  27860. return _this;
  27861. }
  27862. Cylinder.prototype._regenerateVertexData = function () {
  27863. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  27864. };
  27865. Cylinder.prototype.copy = function (id) {
  27866. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  27867. };
  27868. Cylinder.prototype.serialize = function () {
  27869. var serializationObject = _super.prototype.serialize.call(this);
  27870. serializationObject.height = this.height;
  27871. serializationObject.diameterTop = this.diameterTop;
  27872. serializationObject.diameterBottom = this.diameterBottom;
  27873. serializationObject.tessellation = this.tessellation;
  27874. return serializationObject;
  27875. };
  27876. Cylinder.Parse = function (parsedCylinder, scene) {
  27877. if (scene.getGeometryByID(parsedCylinder.id)) {
  27878. return null; // null since geometry could be something else than a cylinder...
  27879. }
  27880. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  27881. if (BABYLON.Tags) {
  27882. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  27883. }
  27884. scene.pushGeometry(cylinder, true);
  27885. return cylinder;
  27886. };
  27887. return Cylinder;
  27888. }(_Primitive));
  27889. Primitives.Cylinder = Cylinder;
  27890. var Torus = (function (_super) {
  27891. __extends(Torus, _super);
  27892. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  27893. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27894. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27895. _this.diameter = diameter;
  27896. _this.thickness = thickness;
  27897. _this.tessellation = tessellation;
  27898. _this.side = side;
  27899. return _this;
  27900. }
  27901. Torus.prototype._regenerateVertexData = function () {
  27902. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  27903. };
  27904. Torus.prototype.copy = function (id) {
  27905. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  27906. };
  27907. Torus.prototype.serialize = function () {
  27908. var serializationObject = _super.prototype.serialize.call(this);
  27909. serializationObject.diameter = this.diameter;
  27910. serializationObject.thickness = this.thickness;
  27911. serializationObject.tessellation = this.tessellation;
  27912. return serializationObject;
  27913. };
  27914. Torus.Parse = function (parsedTorus, scene) {
  27915. if (scene.getGeometryByID(parsedTorus.id)) {
  27916. return null; // null since geometry could be something else than a torus...
  27917. }
  27918. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  27919. if (BABYLON.Tags) {
  27920. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  27921. }
  27922. scene.pushGeometry(torus, true);
  27923. return torus;
  27924. };
  27925. return Torus;
  27926. }(_Primitive));
  27927. Primitives.Torus = Torus;
  27928. var Ground = (function (_super) {
  27929. __extends(Ground, _super);
  27930. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  27931. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27932. _this.width = width;
  27933. _this.height = height;
  27934. _this.subdivisions = subdivisions;
  27935. return _this;
  27936. }
  27937. Ground.prototype._regenerateVertexData = function () {
  27938. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  27939. };
  27940. Ground.prototype.copy = function (id) {
  27941. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  27942. };
  27943. Ground.prototype.serialize = function () {
  27944. var serializationObject = _super.prototype.serialize.call(this);
  27945. serializationObject.width = this.width;
  27946. serializationObject.height = this.height;
  27947. serializationObject.subdivisions = this.subdivisions;
  27948. return serializationObject;
  27949. };
  27950. Ground.Parse = function (parsedGround, scene) {
  27951. if (scene.getGeometryByID(parsedGround.id)) {
  27952. return null; // null since geometry could be something else than a ground...
  27953. }
  27954. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  27955. if (BABYLON.Tags) {
  27956. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  27957. }
  27958. scene.pushGeometry(ground, true);
  27959. return ground;
  27960. };
  27961. return Ground;
  27962. }(_Primitive));
  27963. Primitives.Ground = Ground;
  27964. var TiledGround = (function (_super) {
  27965. __extends(TiledGround, _super);
  27966. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  27967. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27968. _this.xmin = xmin;
  27969. _this.zmin = zmin;
  27970. _this.xmax = xmax;
  27971. _this.zmax = zmax;
  27972. _this.subdivisions = subdivisions;
  27973. _this.precision = precision;
  27974. return _this;
  27975. }
  27976. TiledGround.prototype._regenerateVertexData = function () {
  27977. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  27978. };
  27979. TiledGround.prototype.copy = function (id) {
  27980. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  27981. };
  27982. return TiledGround;
  27983. }(_Primitive));
  27984. Primitives.TiledGround = TiledGround;
  27985. var Plane = (function (_super) {
  27986. __extends(Plane, _super);
  27987. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  27988. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27989. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27990. _this.size = size;
  27991. _this.side = side;
  27992. return _this;
  27993. }
  27994. Plane.prototype._regenerateVertexData = function () {
  27995. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  27996. };
  27997. Plane.prototype.copy = function (id) {
  27998. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27999. };
  28000. Plane.prototype.serialize = function () {
  28001. var serializationObject = _super.prototype.serialize.call(this);
  28002. serializationObject.size = this.size;
  28003. return serializationObject;
  28004. };
  28005. Plane.Parse = function (parsedPlane, scene) {
  28006. if (scene.getGeometryByID(parsedPlane.id)) {
  28007. return null; // null since geometry could be something else than a ground...
  28008. }
  28009. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  28010. if (BABYLON.Tags) {
  28011. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  28012. }
  28013. scene.pushGeometry(plane, true);
  28014. return plane;
  28015. };
  28016. return Plane;
  28017. }(_Primitive));
  28018. Primitives.Plane = Plane;
  28019. var TorusKnot = (function (_super) {
  28020. __extends(TorusKnot, _super);
  28021. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  28022. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28023. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  28024. _this.radius = radius;
  28025. _this.tube = tube;
  28026. _this.radialSegments = radialSegments;
  28027. _this.tubularSegments = tubularSegments;
  28028. _this.p = p;
  28029. _this.q = q;
  28030. _this.side = side;
  28031. return _this;
  28032. }
  28033. TorusKnot.prototype._regenerateVertexData = function () {
  28034. 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 });
  28035. };
  28036. TorusKnot.prototype.copy = function (id) {
  28037. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  28038. };
  28039. TorusKnot.prototype.serialize = function () {
  28040. var serializationObject = _super.prototype.serialize.call(this);
  28041. serializationObject.radius = this.radius;
  28042. serializationObject.tube = this.tube;
  28043. serializationObject.radialSegments = this.radialSegments;
  28044. serializationObject.tubularSegments = this.tubularSegments;
  28045. serializationObject.p = this.p;
  28046. serializationObject.q = this.q;
  28047. return serializationObject;
  28048. };
  28049. ;
  28050. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  28051. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  28052. return null; // null since geometry could be something else than a ground...
  28053. }
  28054. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  28055. if (BABYLON.Tags) {
  28056. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  28057. }
  28058. scene.pushGeometry(torusKnot, true);
  28059. return torusKnot;
  28060. };
  28061. return TorusKnot;
  28062. }(_Primitive));
  28063. Primitives.TorusKnot = TorusKnot;
  28064. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  28065. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  28066. })(BABYLON || (BABYLON = {}));
  28067. //# sourceMappingURL=babylon.geometry.js.map
  28068. var BABYLON;
  28069. (function (BABYLON) {
  28070. var PostProcessManager = (function () {
  28071. function PostProcessManager(scene) {
  28072. this._vertexBuffers = {};
  28073. this._scene = scene;
  28074. }
  28075. PostProcessManager.prototype._prepareBuffers = function () {
  28076. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  28077. return;
  28078. }
  28079. // VBO
  28080. var vertices = [];
  28081. vertices.push(1, 1);
  28082. vertices.push(-1, 1);
  28083. vertices.push(-1, -1);
  28084. vertices.push(1, -1);
  28085. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  28086. // Indices
  28087. var indices = [];
  28088. indices.push(0);
  28089. indices.push(1);
  28090. indices.push(2);
  28091. indices.push(0);
  28092. indices.push(2);
  28093. indices.push(3);
  28094. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  28095. };
  28096. // Methods
  28097. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  28098. var postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  28099. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28100. return false;
  28101. }
  28102. postProcesses[0].activate(this._scene.activeCamera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  28103. return true;
  28104. };
  28105. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  28106. var engine = this._scene.getEngine();
  28107. for (var index = 0; index < postProcesses.length; index++) {
  28108. if (index < postProcesses.length - 1) {
  28109. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28110. }
  28111. else {
  28112. if (targetTexture) {
  28113. engine.bindFramebuffer(targetTexture);
  28114. }
  28115. else {
  28116. engine.restoreDefaultFramebuffer();
  28117. }
  28118. }
  28119. var pp = postProcesses[index];
  28120. var effect = pp.apply();
  28121. if (effect) {
  28122. pp.onBeforeRenderObservable.notifyObservers(effect);
  28123. // VBOs
  28124. this._prepareBuffers();
  28125. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28126. // Draw order
  28127. engine.draw(true, 0, 6);
  28128. pp.onAfterRenderObservable.notifyObservers(effect);
  28129. }
  28130. }
  28131. // Restore depth buffer
  28132. engine.setDepthBuffer(true);
  28133. engine.setDepthWrite(true);
  28134. };
  28135. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  28136. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  28137. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28138. return;
  28139. }
  28140. var engine = this._scene.getEngine();
  28141. for (var index = 0, len = postProcesses.length; index < len; index++) {
  28142. if (index < len - 1) {
  28143. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28144. }
  28145. else {
  28146. if (targetTexture) {
  28147. engine.bindFramebuffer(targetTexture, faceIndex);
  28148. }
  28149. else {
  28150. engine.restoreDefaultFramebuffer();
  28151. }
  28152. }
  28153. if (doNotPresent) {
  28154. break;
  28155. }
  28156. var pp = postProcesses[index];
  28157. var effect = pp.apply();
  28158. if (effect) {
  28159. pp.onBeforeRenderObservable.notifyObservers(effect);
  28160. // VBOs
  28161. this._prepareBuffers();
  28162. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28163. // Draw order
  28164. engine.draw(true, 0, 6);
  28165. pp.onAfterRenderObservable.notifyObservers(effect);
  28166. }
  28167. }
  28168. // Restore states
  28169. engine.setDepthBuffer(true);
  28170. engine.setDepthWrite(true);
  28171. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28172. };
  28173. PostProcessManager.prototype.dispose = function () {
  28174. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28175. if (buffer) {
  28176. buffer.dispose();
  28177. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28178. }
  28179. if (this._indexBuffer) {
  28180. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28181. this._indexBuffer = null;
  28182. }
  28183. };
  28184. return PostProcessManager;
  28185. }());
  28186. BABYLON.PostProcessManager = PostProcessManager;
  28187. })(BABYLON || (BABYLON = {}));
  28188. //# sourceMappingURL=babylon.postProcessManager.js.map
  28189. var BABYLON;
  28190. (function (BABYLON) {
  28191. var AnimationRange = (function () {
  28192. function AnimationRange(name, from, to) {
  28193. this.name = name;
  28194. this.from = from;
  28195. this.to = to;
  28196. }
  28197. AnimationRange.prototype.clone = function () {
  28198. return new AnimationRange(this.name, this.from, this.to);
  28199. };
  28200. return AnimationRange;
  28201. }());
  28202. BABYLON.AnimationRange = AnimationRange;
  28203. /**
  28204. * Composed of a frame, and an action function
  28205. */
  28206. var AnimationEvent = (function () {
  28207. function AnimationEvent(frame, action, onlyOnce) {
  28208. this.frame = frame;
  28209. this.action = action;
  28210. this.onlyOnce = onlyOnce;
  28211. this.isDone = false;
  28212. }
  28213. return AnimationEvent;
  28214. }());
  28215. BABYLON.AnimationEvent = AnimationEvent;
  28216. var PathCursor = (function () {
  28217. function PathCursor(path) {
  28218. this.path = path;
  28219. this._onchange = new Array();
  28220. this.value = 0;
  28221. this.animations = new Array();
  28222. }
  28223. PathCursor.prototype.getPoint = function () {
  28224. var point = this.path.getPointAtLengthPosition(this.value);
  28225. return new BABYLON.Vector3(point.x, 0, point.y);
  28226. };
  28227. PathCursor.prototype.moveAhead = function (step) {
  28228. if (step === void 0) { step = 0.002; }
  28229. this.move(step);
  28230. return this;
  28231. };
  28232. PathCursor.prototype.moveBack = function (step) {
  28233. if (step === void 0) { step = 0.002; }
  28234. this.move(-step);
  28235. return this;
  28236. };
  28237. PathCursor.prototype.move = function (step) {
  28238. if (Math.abs(step) > 1) {
  28239. throw "step size should be less than 1.";
  28240. }
  28241. this.value += step;
  28242. this.ensureLimits();
  28243. this.raiseOnChange();
  28244. return this;
  28245. };
  28246. PathCursor.prototype.ensureLimits = function () {
  28247. while (this.value > 1) {
  28248. this.value -= 1;
  28249. }
  28250. while (this.value < 0) {
  28251. this.value += 1;
  28252. }
  28253. return this;
  28254. };
  28255. // used by animation engine
  28256. PathCursor.prototype.markAsDirty = function (propertyName) {
  28257. this.ensureLimits();
  28258. this.raiseOnChange();
  28259. return this;
  28260. };
  28261. PathCursor.prototype.raiseOnChange = function () {
  28262. var _this = this;
  28263. this._onchange.forEach(function (f) { return f(_this); });
  28264. return this;
  28265. };
  28266. PathCursor.prototype.onchange = function (f) {
  28267. this._onchange.push(f);
  28268. return this;
  28269. };
  28270. return PathCursor;
  28271. }());
  28272. BABYLON.PathCursor = PathCursor;
  28273. var Animation = (function () {
  28274. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  28275. this.name = name;
  28276. this.targetProperty = targetProperty;
  28277. this.framePerSecond = framePerSecond;
  28278. this.dataType = dataType;
  28279. this.loopMode = loopMode;
  28280. this.enableBlending = enableBlending;
  28281. this._offsetsCache = {};
  28282. this._highLimitsCache = {};
  28283. this._stopped = false;
  28284. this._blendingFactor = 0;
  28285. // The set of event that will be linked to this animation
  28286. this._events = new Array();
  28287. this.allowMatricesInterpolation = false;
  28288. this.blendingSpeed = 0.01;
  28289. this._ranges = {};
  28290. this.targetPropertyPath = targetProperty.split(".");
  28291. this.dataType = dataType;
  28292. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  28293. }
  28294. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  28295. var dataType = undefined;
  28296. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  28297. dataType = Animation.ANIMATIONTYPE_FLOAT;
  28298. }
  28299. else if (from instanceof BABYLON.Quaternion) {
  28300. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  28301. }
  28302. else if (from instanceof BABYLON.Vector3) {
  28303. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  28304. }
  28305. else if (from instanceof BABYLON.Vector2) {
  28306. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  28307. }
  28308. else if (from instanceof BABYLON.Color3) {
  28309. dataType = Animation.ANIMATIONTYPE_COLOR3;
  28310. }
  28311. else if (from instanceof BABYLON.Size) {
  28312. dataType = Animation.ANIMATIONTYPE_SIZE;
  28313. }
  28314. if (dataType == undefined) {
  28315. return null;
  28316. }
  28317. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  28318. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  28319. animation.setKeys(keys);
  28320. if (easingFunction !== undefined) {
  28321. animation.setEasingFunction(easingFunction);
  28322. }
  28323. return animation;
  28324. };
  28325. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  28326. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  28327. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  28328. };
  28329. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  28330. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  28331. node.animations.push(animation);
  28332. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  28333. };
  28334. // Methods
  28335. /**
  28336. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28337. */
  28338. Animation.prototype.toString = function (fullDetails) {
  28339. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  28340. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  28341. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  28342. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  28343. if (fullDetails) {
  28344. ret += ", Ranges: {";
  28345. var first = true;
  28346. for (var name in this._ranges) {
  28347. if (first) {
  28348. ret += ", ";
  28349. first = false;
  28350. }
  28351. ret += name;
  28352. }
  28353. ret += "}";
  28354. }
  28355. return ret;
  28356. };
  28357. /**
  28358. * Add an event to this animation.
  28359. */
  28360. Animation.prototype.addEvent = function (event) {
  28361. this._events.push(event);
  28362. };
  28363. /**
  28364. * Remove all events found at the given frame
  28365. * @param frame
  28366. */
  28367. Animation.prototype.removeEvents = function (frame) {
  28368. for (var index = 0; index < this._events.length; index++) {
  28369. if (this._events[index].frame === frame) {
  28370. this._events.splice(index, 1);
  28371. index--;
  28372. }
  28373. }
  28374. };
  28375. Animation.prototype.createRange = function (name, from, to) {
  28376. // check name not already in use; could happen for bones after serialized
  28377. if (!this._ranges[name]) {
  28378. this._ranges[name] = new AnimationRange(name, from, to);
  28379. }
  28380. };
  28381. Animation.prototype.deleteRange = function (name, deleteFrames) {
  28382. if (deleteFrames === void 0) { deleteFrames = true; }
  28383. if (this._ranges[name]) {
  28384. if (deleteFrames) {
  28385. var from = this._ranges[name].from;
  28386. var to = this._ranges[name].to;
  28387. // this loop MUST go high to low for multiple splices to work
  28388. for (var key = this._keys.length - 1; key >= 0; key--) {
  28389. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  28390. this._keys.splice(key, 1);
  28391. }
  28392. }
  28393. }
  28394. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  28395. }
  28396. };
  28397. Animation.prototype.getRange = function (name) {
  28398. return this._ranges[name];
  28399. };
  28400. Animation.prototype.reset = function () {
  28401. this._offsetsCache = {};
  28402. this._highLimitsCache = {};
  28403. this.currentFrame = 0;
  28404. this._blendingFactor = 0;
  28405. this._originalBlendValue = null;
  28406. };
  28407. Animation.prototype.isStopped = function () {
  28408. return this._stopped;
  28409. };
  28410. Animation.prototype.getKeys = function () {
  28411. return this._keys;
  28412. };
  28413. Animation.prototype.getHighestFrame = function () {
  28414. var ret = 0;
  28415. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  28416. if (ret < this._keys[key].frame) {
  28417. ret = this._keys[key].frame;
  28418. }
  28419. }
  28420. return ret;
  28421. };
  28422. Animation.prototype.getEasingFunction = function () {
  28423. return this._easingFunction;
  28424. };
  28425. Animation.prototype.setEasingFunction = function (easingFunction) {
  28426. this._easingFunction = easingFunction;
  28427. };
  28428. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  28429. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  28430. };
  28431. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  28432. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  28433. };
  28434. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  28435. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  28436. };
  28437. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  28438. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  28439. };
  28440. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  28441. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  28442. };
  28443. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  28444. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  28445. };
  28446. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  28447. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  28448. };
  28449. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  28450. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  28451. };
  28452. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  28453. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  28454. };
  28455. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  28456. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  28457. };
  28458. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  28459. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  28460. };
  28461. Animation.prototype.clone = function () {
  28462. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  28463. clone.enableBlending = this.enableBlending;
  28464. clone.blendingSpeed = this.blendingSpeed;
  28465. if (this._keys) {
  28466. clone.setKeys(this._keys);
  28467. }
  28468. if (this._ranges) {
  28469. clone._ranges = {};
  28470. for (var name in this._ranges) {
  28471. clone._ranges[name] = this._ranges[name].clone();
  28472. }
  28473. }
  28474. return clone;
  28475. };
  28476. Animation.prototype.setKeys = function (values) {
  28477. this._keys = values.slice(0);
  28478. this._offsetsCache = {};
  28479. this._highLimitsCache = {};
  28480. };
  28481. Animation.prototype._getKeyValue = function (value) {
  28482. if (typeof value === "function") {
  28483. return value();
  28484. }
  28485. return value;
  28486. };
  28487. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  28488. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  28489. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  28490. }
  28491. this.currentFrame = currentFrame;
  28492. // Try to get a hash to find the right key
  28493. 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));
  28494. if (this._keys[startKeyIndex].frame >= currentFrame) {
  28495. while (startKeyIndex - 1 >= 0 && this._keys[startKeyIndex].frame >= currentFrame) {
  28496. startKeyIndex--;
  28497. }
  28498. }
  28499. for (var key = startKeyIndex; key < this._keys.length; key++) {
  28500. var endKey = this._keys[key + 1];
  28501. if (endKey.frame >= currentFrame) {
  28502. var startKey = this._keys[key];
  28503. var startValue = this._getKeyValue(startKey.value);
  28504. var endValue = this._getKeyValue(endKey.value);
  28505. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  28506. var frameDelta = endKey.frame - startKey.frame;
  28507. // gradient : percent of currentFrame between the frame inf and the frame sup
  28508. var gradient = (currentFrame - startKey.frame) / frameDelta;
  28509. // check for easingFunction and correction of gradient
  28510. if (this._easingFunction != null) {
  28511. gradient = this._easingFunction.ease(gradient);
  28512. }
  28513. switch (this.dataType) {
  28514. // Float
  28515. case Animation.ANIMATIONTYPE_FLOAT:
  28516. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  28517. switch (loopMode) {
  28518. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28519. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28520. return floatValue;
  28521. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28522. return offsetValue * repeatCount + floatValue;
  28523. }
  28524. break;
  28525. // Quaternion
  28526. case Animation.ANIMATIONTYPE_QUATERNION:
  28527. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  28528. switch (loopMode) {
  28529. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28530. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28531. return quatValue;
  28532. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28533. return quatValue.add(offsetValue.scale(repeatCount));
  28534. }
  28535. return quatValue;
  28536. // Vector3
  28537. case Animation.ANIMATIONTYPE_VECTOR3:
  28538. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  28539. switch (loopMode) {
  28540. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28541. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28542. return vec3Value;
  28543. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28544. return vec3Value.add(offsetValue.scale(repeatCount));
  28545. }
  28546. // Vector2
  28547. case Animation.ANIMATIONTYPE_VECTOR2:
  28548. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  28549. switch (loopMode) {
  28550. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28551. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28552. return vec2Value;
  28553. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28554. return vec2Value.add(offsetValue.scale(repeatCount));
  28555. }
  28556. // Size
  28557. case Animation.ANIMATIONTYPE_SIZE:
  28558. switch (loopMode) {
  28559. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28560. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28561. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  28562. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28563. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28564. }
  28565. // Color3
  28566. case Animation.ANIMATIONTYPE_COLOR3:
  28567. switch (loopMode) {
  28568. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28569. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28570. return this.color3InterpolateFunction(startValue, endValue, gradient);
  28571. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28572. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28573. }
  28574. // Matrix
  28575. case Animation.ANIMATIONTYPE_MATRIX:
  28576. switch (loopMode) {
  28577. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28578. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28579. if (this.allowMatricesInterpolation) {
  28580. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  28581. }
  28582. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28583. return startValue;
  28584. }
  28585. default:
  28586. break;
  28587. }
  28588. break;
  28589. }
  28590. }
  28591. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  28592. };
  28593. Animation.prototype.setValue = function (currentValue, blend) {
  28594. if (blend === void 0) { blend = false; }
  28595. // Set value
  28596. var path;
  28597. var destination;
  28598. if (this.targetPropertyPath.length > 1) {
  28599. var property = this._target[this.targetPropertyPath[0]];
  28600. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  28601. property = property[this.targetPropertyPath[index]];
  28602. }
  28603. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  28604. destination = property;
  28605. }
  28606. else {
  28607. path = this.targetPropertyPath[0];
  28608. destination = this._target;
  28609. }
  28610. // Blending
  28611. if (this.enableBlending && this._blendingFactor <= 1.0) {
  28612. if (!this._originalBlendValue) {
  28613. if (destination[path].clone) {
  28614. this._originalBlendValue = destination[path].clone();
  28615. }
  28616. else {
  28617. this._originalBlendValue = destination[path];
  28618. }
  28619. }
  28620. if (this._originalBlendValue.prototype) {
  28621. if (this._originalBlendValue.prototype.Lerp) {
  28622. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  28623. }
  28624. else {
  28625. destination[path] = currentValue;
  28626. }
  28627. }
  28628. else if (this._originalBlendValue.m) {
  28629. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  28630. }
  28631. else {
  28632. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  28633. }
  28634. this._blendingFactor += this.blendingSpeed;
  28635. }
  28636. else {
  28637. destination[path] = currentValue;
  28638. }
  28639. if (this._target.markAsDirty) {
  28640. this._target.markAsDirty(this.targetProperty);
  28641. }
  28642. };
  28643. Animation.prototype.goToFrame = function (frame) {
  28644. if (frame < this._keys[0].frame) {
  28645. frame = this._keys[0].frame;
  28646. }
  28647. else if (frame > this._keys[this._keys.length - 1].frame) {
  28648. frame = this._keys[this._keys.length - 1].frame;
  28649. }
  28650. var currentValue = this._interpolate(frame, 0, this.loopMode);
  28651. this.setValue(currentValue);
  28652. };
  28653. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  28654. if (blend === void 0) { blend = false; }
  28655. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  28656. this._stopped = true;
  28657. return false;
  28658. }
  28659. var returnValue = true;
  28660. // Adding a start key at frame 0 if missing
  28661. if (this._keys[0].frame !== 0) {
  28662. var newKey = { frame: 0, value: this._keys[0].value };
  28663. this._keys.splice(0, 0, newKey);
  28664. }
  28665. // Check limits
  28666. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  28667. from = this._keys[0].frame;
  28668. }
  28669. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  28670. to = this._keys[this._keys.length - 1].frame;
  28671. }
  28672. //to and from cannot be the same key
  28673. if (from === to) {
  28674. from++;
  28675. }
  28676. // Compute ratio
  28677. var range = to - from;
  28678. var offsetValue;
  28679. // ratio represents the frame delta between from and to
  28680. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  28681. var highLimitValue = 0;
  28682. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  28683. returnValue = false;
  28684. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  28685. }
  28686. else {
  28687. // Get max value if required
  28688. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  28689. var keyOffset = to.toString() + from.toString();
  28690. if (!this._offsetsCache[keyOffset]) {
  28691. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  28692. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  28693. switch (this.dataType) {
  28694. // Float
  28695. case Animation.ANIMATIONTYPE_FLOAT:
  28696. this._offsetsCache[keyOffset] = toValue - fromValue;
  28697. break;
  28698. // Quaternion
  28699. case Animation.ANIMATIONTYPE_QUATERNION:
  28700. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28701. break;
  28702. // Vector3
  28703. case Animation.ANIMATIONTYPE_VECTOR3:
  28704. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28705. // Vector2
  28706. case Animation.ANIMATIONTYPE_VECTOR2:
  28707. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28708. // Size
  28709. case Animation.ANIMATIONTYPE_SIZE:
  28710. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28711. // Color3
  28712. case Animation.ANIMATIONTYPE_COLOR3:
  28713. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28714. default:
  28715. break;
  28716. }
  28717. this._highLimitsCache[keyOffset] = toValue;
  28718. }
  28719. highLimitValue = this._highLimitsCache[keyOffset];
  28720. offsetValue = this._offsetsCache[keyOffset];
  28721. }
  28722. }
  28723. if (offsetValue === undefined) {
  28724. switch (this.dataType) {
  28725. // Float
  28726. case Animation.ANIMATIONTYPE_FLOAT:
  28727. offsetValue = 0;
  28728. break;
  28729. // Quaternion
  28730. case Animation.ANIMATIONTYPE_QUATERNION:
  28731. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  28732. break;
  28733. // Vector3
  28734. case Animation.ANIMATIONTYPE_VECTOR3:
  28735. offsetValue = BABYLON.Vector3.Zero();
  28736. break;
  28737. // Vector2
  28738. case Animation.ANIMATIONTYPE_VECTOR2:
  28739. offsetValue = BABYLON.Vector2.Zero();
  28740. break;
  28741. // Size
  28742. case Animation.ANIMATIONTYPE_SIZE:
  28743. offsetValue = BABYLON.Size.Zero();
  28744. break;
  28745. // Color3
  28746. case Animation.ANIMATIONTYPE_COLOR3:
  28747. offsetValue = BABYLON.Color3.Black();
  28748. }
  28749. }
  28750. // Compute value
  28751. var repeatCount = (ratio / range) >> 0;
  28752. var currentFrame = returnValue ? from + ratio % range : to;
  28753. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  28754. // Set value
  28755. this.setValue(currentValue);
  28756. // Check events
  28757. for (var index = 0; index < this._events.length; index++) {
  28758. if (currentFrame >= this._events[index].frame) {
  28759. var event = this._events[index];
  28760. if (!event.isDone) {
  28761. // If event should be done only once, remove it.
  28762. if (event.onlyOnce) {
  28763. this._events.splice(index, 1);
  28764. index--;
  28765. }
  28766. event.isDone = true;
  28767. event.action();
  28768. } // Don't do anything if the event has already be done.
  28769. }
  28770. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  28771. // reset event, the animation is looping
  28772. this._events[index].isDone = false;
  28773. }
  28774. }
  28775. if (!returnValue) {
  28776. this._stopped = true;
  28777. }
  28778. return returnValue;
  28779. };
  28780. Animation.prototype.serialize = function () {
  28781. var serializationObject = {};
  28782. serializationObject.name = this.name;
  28783. serializationObject.property = this.targetProperty;
  28784. serializationObject.framePerSecond = this.framePerSecond;
  28785. serializationObject.dataType = this.dataType;
  28786. serializationObject.loopBehavior = this.loopMode;
  28787. serializationObject.enableBlending = this.enableBlending;
  28788. serializationObject.blendingSpeed = this.blendingSpeed;
  28789. var dataType = this.dataType;
  28790. serializationObject.keys = [];
  28791. var keys = this.getKeys();
  28792. for (var index = 0; index < keys.length; index++) {
  28793. var animationKey = keys[index];
  28794. var key = {};
  28795. key.frame = animationKey.frame;
  28796. switch (dataType) {
  28797. case Animation.ANIMATIONTYPE_FLOAT:
  28798. key.values = [animationKey.value];
  28799. break;
  28800. case Animation.ANIMATIONTYPE_QUATERNION:
  28801. case Animation.ANIMATIONTYPE_MATRIX:
  28802. case Animation.ANIMATIONTYPE_VECTOR3:
  28803. case Animation.ANIMATIONTYPE_COLOR3:
  28804. key.values = animationKey.value.asArray();
  28805. break;
  28806. }
  28807. serializationObject.keys.push(key);
  28808. }
  28809. serializationObject.ranges = [];
  28810. for (var name in this._ranges) {
  28811. var range = {};
  28812. range.name = name;
  28813. range.from = this._ranges[name].from;
  28814. range.to = this._ranges[name].to;
  28815. serializationObject.ranges.push(range);
  28816. }
  28817. return serializationObject;
  28818. };
  28819. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  28820. get: function () {
  28821. return Animation._ANIMATIONTYPE_FLOAT;
  28822. },
  28823. enumerable: true,
  28824. configurable: true
  28825. });
  28826. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  28827. get: function () {
  28828. return Animation._ANIMATIONTYPE_VECTOR3;
  28829. },
  28830. enumerable: true,
  28831. configurable: true
  28832. });
  28833. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  28834. get: function () {
  28835. return Animation._ANIMATIONTYPE_VECTOR2;
  28836. },
  28837. enumerable: true,
  28838. configurable: true
  28839. });
  28840. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  28841. get: function () {
  28842. return Animation._ANIMATIONTYPE_SIZE;
  28843. },
  28844. enumerable: true,
  28845. configurable: true
  28846. });
  28847. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  28848. get: function () {
  28849. return Animation._ANIMATIONTYPE_QUATERNION;
  28850. },
  28851. enumerable: true,
  28852. configurable: true
  28853. });
  28854. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  28855. get: function () {
  28856. return Animation._ANIMATIONTYPE_MATRIX;
  28857. },
  28858. enumerable: true,
  28859. configurable: true
  28860. });
  28861. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  28862. get: function () {
  28863. return Animation._ANIMATIONTYPE_COLOR3;
  28864. },
  28865. enumerable: true,
  28866. configurable: true
  28867. });
  28868. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  28869. get: function () {
  28870. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  28871. },
  28872. enumerable: true,
  28873. configurable: true
  28874. });
  28875. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  28876. get: function () {
  28877. return Animation._ANIMATIONLOOPMODE_CYCLE;
  28878. },
  28879. enumerable: true,
  28880. configurable: true
  28881. });
  28882. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  28883. get: function () {
  28884. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  28885. },
  28886. enumerable: true,
  28887. configurable: true
  28888. });
  28889. Animation.Parse = function (parsedAnimation) {
  28890. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  28891. var dataType = parsedAnimation.dataType;
  28892. var keys = [];
  28893. var data;
  28894. var index;
  28895. if (parsedAnimation.enableBlending) {
  28896. animation.enableBlending = parsedAnimation.enableBlending;
  28897. }
  28898. if (parsedAnimation.blendingSpeed) {
  28899. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  28900. }
  28901. for (index = 0; index < parsedAnimation.keys.length; index++) {
  28902. var key = parsedAnimation.keys[index];
  28903. switch (dataType) {
  28904. case Animation.ANIMATIONTYPE_FLOAT:
  28905. data = key.values[0];
  28906. break;
  28907. case Animation.ANIMATIONTYPE_QUATERNION:
  28908. data = BABYLON.Quaternion.FromArray(key.values);
  28909. break;
  28910. case Animation.ANIMATIONTYPE_MATRIX:
  28911. data = BABYLON.Matrix.FromArray(key.values);
  28912. break;
  28913. case Animation.ANIMATIONTYPE_COLOR3:
  28914. data = BABYLON.Color3.FromArray(key.values);
  28915. break;
  28916. case Animation.ANIMATIONTYPE_VECTOR3:
  28917. default:
  28918. data = BABYLON.Vector3.FromArray(key.values);
  28919. break;
  28920. }
  28921. keys.push({
  28922. frame: key.frame,
  28923. value: data
  28924. });
  28925. }
  28926. animation.setKeys(keys);
  28927. if (parsedAnimation.ranges) {
  28928. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  28929. data = parsedAnimation.ranges[index];
  28930. animation.createRange(data.name, data.from, data.to);
  28931. }
  28932. }
  28933. return animation;
  28934. };
  28935. Animation.AppendSerializedAnimations = function (source, destination) {
  28936. if (source.animations) {
  28937. destination.animations = [];
  28938. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  28939. var animation = source.animations[animationIndex];
  28940. destination.animations.push(animation.serialize());
  28941. }
  28942. }
  28943. };
  28944. return Animation;
  28945. }());
  28946. // Statics
  28947. Animation._ANIMATIONTYPE_FLOAT = 0;
  28948. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  28949. Animation._ANIMATIONTYPE_QUATERNION = 2;
  28950. Animation._ANIMATIONTYPE_MATRIX = 3;
  28951. Animation._ANIMATIONTYPE_COLOR3 = 4;
  28952. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  28953. Animation._ANIMATIONTYPE_SIZE = 6;
  28954. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  28955. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  28956. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  28957. BABYLON.Animation = Animation;
  28958. })(BABYLON || (BABYLON = {}));
  28959. //# sourceMappingURL=babylon.animation.js.map
  28960. var BABYLON;
  28961. (function (BABYLON) {
  28962. var Animatable = (function () {
  28963. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  28964. if (fromFrame === void 0) { fromFrame = 0; }
  28965. if (toFrame === void 0) { toFrame = 100; }
  28966. if (loopAnimation === void 0) { loopAnimation = false; }
  28967. if (speedRatio === void 0) { speedRatio = 1.0; }
  28968. this.target = target;
  28969. this.fromFrame = fromFrame;
  28970. this.toFrame = toFrame;
  28971. this.loopAnimation = loopAnimation;
  28972. this.speedRatio = speedRatio;
  28973. this.onAnimationEnd = onAnimationEnd;
  28974. this._localDelayOffset = null;
  28975. this._pausedDelay = null;
  28976. this._animations = new Array();
  28977. this._paused = false;
  28978. this.animationStarted = false;
  28979. if (animations) {
  28980. this.appendAnimations(target, animations);
  28981. }
  28982. this._scene = scene;
  28983. scene._activeAnimatables.push(this);
  28984. }
  28985. // Methods
  28986. Animatable.prototype.getAnimations = function () {
  28987. return this._animations;
  28988. };
  28989. Animatable.prototype.appendAnimations = function (target, animations) {
  28990. for (var index = 0; index < animations.length; index++) {
  28991. var animation = animations[index];
  28992. animation._target = target;
  28993. this._animations.push(animation);
  28994. }
  28995. };
  28996. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  28997. var animations = this._animations;
  28998. for (var index = 0; index < animations.length; index++) {
  28999. if (animations[index].targetProperty === property) {
  29000. return animations[index];
  29001. }
  29002. }
  29003. return null;
  29004. };
  29005. Animatable.prototype.reset = function () {
  29006. var animations = this._animations;
  29007. for (var index = 0; index < animations.length; index++) {
  29008. animations[index].reset();
  29009. }
  29010. this._localDelayOffset = null;
  29011. this._pausedDelay = null;
  29012. };
  29013. Animatable.prototype.enableBlending = function (blendingSpeed) {
  29014. var animations = this._animations;
  29015. for (var index = 0; index < animations.length; index++) {
  29016. animations[index].enableBlending = true;
  29017. animations[index].blendingSpeed = blendingSpeed;
  29018. }
  29019. };
  29020. Animatable.prototype.disableBlending = function () {
  29021. var animations = this._animations;
  29022. for (var index = 0; index < animations.length; index++) {
  29023. animations[index].enableBlending = false;
  29024. }
  29025. };
  29026. Animatable.prototype.goToFrame = function (frame) {
  29027. var animations = this._animations;
  29028. if (animations[0]) {
  29029. var fps = animations[0].framePerSecond;
  29030. var currentFrame = animations[0].currentFrame;
  29031. var adjustTime = frame - currentFrame;
  29032. var delay = adjustTime * 1000 / fps;
  29033. this._localDelayOffset -= delay;
  29034. }
  29035. for (var index = 0; index < animations.length; index++) {
  29036. animations[index].goToFrame(frame);
  29037. }
  29038. };
  29039. Animatable.prototype.pause = function () {
  29040. if (this._paused) {
  29041. return;
  29042. }
  29043. this._paused = true;
  29044. };
  29045. Animatable.prototype.restart = function () {
  29046. this._paused = false;
  29047. };
  29048. Animatable.prototype.stop = function (animationName) {
  29049. if (animationName) {
  29050. var idx = this._scene._activeAnimatables.indexOf(this);
  29051. if (idx > -1) {
  29052. var animations = this._animations;
  29053. for (var index = animations.length - 1; index >= 0; index--) {
  29054. if (typeof animationName === "string" && animations[index].name != animationName) {
  29055. continue;
  29056. }
  29057. animations[index].reset();
  29058. animations.splice(index, 1);
  29059. }
  29060. if (animations.length == 0) {
  29061. this._scene._activeAnimatables.splice(idx, 1);
  29062. if (this.onAnimationEnd) {
  29063. this.onAnimationEnd();
  29064. }
  29065. }
  29066. }
  29067. }
  29068. else {
  29069. var index = this._scene._activeAnimatables.indexOf(this);
  29070. if (index > -1) {
  29071. this._scene._activeAnimatables.splice(index, 1);
  29072. var animations = this._animations;
  29073. for (var index = 0; index < animations.length; index++) {
  29074. animations[index].reset();
  29075. }
  29076. if (this.onAnimationEnd) {
  29077. this.onAnimationEnd();
  29078. }
  29079. }
  29080. }
  29081. };
  29082. Animatable.prototype._animate = function (delay) {
  29083. if (this._paused) {
  29084. this.animationStarted = false;
  29085. if (this._pausedDelay === null) {
  29086. this._pausedDelay = delay;
  29087. }
  29088. return true;
  29089. }
  29090. if (this._localDelayOffset === null) {
  29091. this._localDelayOffset = delay;
  29092. }
  29093. else if (this._pausedDelay !== null) {
  29094. this._localDelayOffset += delay - this._pausedDelay;
  29095. this._pausedDelay = null;
  29096. }
  29097. // Animating
  29098. var running = false;
  29099. var animations = this._animations;
  29100. var index;
  29101. for (index = 0; index < animations.length; index++) {
  29102. var animation = animations[index];
  29103. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  29104. running = running || isRunning;
  29105. }
  29106. this.animationStarted = running;
  29107. if (!running) {
  29108. // Remove from active animatables
  29109. index = this._scene._activeAnimatables.indexOf(this);
  29110. this._scene._activeAnimatables.splice(index, 1);
  29111. }
  29112. if (!running && this.onAnimationEnd) {
  29113. this.onAnimationEnd();
  29114. this.onAnimationEnd = null;
  29115. }
  29116. return running;
  29117. };
  29118. return Animatable;
  29119. }());
  29120. BABYLON.Animatable = Animatable;
  29121. })(BABYLON || (BABYLON = {}));
  29122. //# sourceMappingURL=babylon.animatable.js.map
  29123. var BABYLON;
  29124. (function (BABYLON) {
  29125. var EasingFunction = (function () {
  29126. function EasingFunction() {
  29127. // Properties
  29128. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  29129. }
  29130. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  29131. get: function () {
  29132. return EasingFunction._EASINGMODE_EASEIN;
  29133. },
  29134. enumerable: true,
  29135. configurable: true
  29136. });
  29137. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  29138. get: function () {
  29139. return EasingFunction._EASINGMODE_EASEOUT;
  29140. },
  29141. enumerable: true,
  29142. configurable: true
  29143. });
  29144. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  29145. get: function () {
  29146. return EasingFunction._EASINGMODE_EASEINOUT;
  29147. },
  29148. enumerable: true,
  29149. configurable: true
  29150. });
  29151. EasingFunction.prototype.setEasingMode = function (easingMode) {
  29152. var n = Math.min(Math.max(easingMode, 0), 2);
  29153. this._easingMode = n;
  29154. };
  29155. EasingFunction.prototype.getEasingMode = function () {
  29156. return this._easingMode;
  29157. };
  29158. EasingFunction.prototype.easeInCore = function (gradient) {
  29159. throw new Error('You must implement this method');
  29160. };
  29161. EasingFunction.prototype.ease = function (gradient) {
  29162. switch (this._easingMode) {
  29163. case EasingFunction.EASINGMODE_EASEIN:
  29164. return this.easeInCore(gradient);
  29165. case EasingFunction.EASINGMODE_EASEOUT:
  29166. return (1 - this.easeInCore(1 - gradient));
  29167. }
  29168. if (gradient >= 0.5) {
  29169. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  29170. }
  29171. return (this.easeInCore(gradient * 2) * 0.5);
  29172. };
  29173. return EasingFunction;
  29174. }());
  29175. //Statics
  29176. EasingFunction._EASINGMODE_EASEIN = 0;
  29177. EasingFunction._EASINGMODE_EASEOUT = 1;
  29178. EasingFunction._EASINGMODE_EASEINOUT = 2;
  29179. BABYLON.EasingFunction = EasingFunction;
  29180. var CircleEase = (function (_super) {
  29181. __extends(CircleEase, _super);
  29182. function CircleEase() {
  29183. return _super !== null && _super.apply(this, arguments) || this;
  29184. }
  29185. CircleEase.prototype.easeInCore = function (gradient) {
  29186. gradient = Math.max(0, Math.min(1, gradient));
  29187. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  29188. };
  29189. return CircleEase;
  29190. }(EasingFunction));
  29191. BABYLON.CircleEase = CircleEase;
  29192. var BackEase = (function (_super) {
  29193. __extends(BackEase, _super);
  29194. function BackEase(amplitude) {
  29195. if (amplitude === void 0) { amplitude = 1; }
  29196. var _this = _super.call(this) || this;
  29197. _this.amplitude = amplitude;
  29198. return _this;
  29199. }
  29200. BackEase.prototype.easeInCore = function (gradient) {
  29201. var num = Math.max(0, this.amplitude);
  29202. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  29203. };
  29204. return BackEase;
  29205. }(EasingFunction));
  29206. BABYLON.BackEase = BackEase;
  29207. var BounceEase = (function (_super) {
  29208. __extends(BounceEase, _super);
  29209. function BounceEase(bounces, bounciness) {
  29210. if (bounces === void 0) { bounces = 3; }
  29211. if (bounciness === void 0) { bounciness = 2; }
  29212. var _this = _super.call(this) || this;
  29213. _this.bounces = bounces;
  29214. _this.bounciness = bounciness;
  29215. return _this;
  29216. }
  29217. BounceEase.prototype.easeInCore = function (gradient) {
  29218. var y = Math.max(0.0, this.bounces);
  29219. var bounciness = this.bounciness;
  29220. if (bounciness <= 1.0) {
  29221. bounciness = 1.001;
  29222. }
  29223. var num9 = Math.pow(bounciness, y);
  29224. var num5 = 1.0 - bounciness;
  29225. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  29226. var num15 = gradient * num4;
  29227. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  29228. var num3 = Math.floor(num65);
  29229. var num13 = num3 + 1.0;
  29230. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  29231. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  29232. var num7 = (num8 + num12) * 0.5;
  29233. var num6 = gradient - num7;
  29234. var num2 = num7 - num8;
  29235. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  29236. };
  29237. return BounceEase;
  29238. }(EasingFunction));
  29239. BABYLON.BounceEase = BounceEase;
  29240. var CubicEase = (function (_super) {
  29241. __extends(CubicEase, _super);
  29242. function CubicEase() {
  29243. return _super !== null && _super.apply(this, arguments) || this;
  29244. }
  29245. CubicEase.prototype.easeInCore = function (gradient) {
  29246. return (gradient * gradient * gradient);
  29247. };
  29248. return CubicEase;
  29249. }(EasingFunction));
  29250. BABYLON.CubicEase = CubicEase;
  29251. var ElasticEase = (function (_super) {
  29252. __extends(ElasticEase, _super);
  29253. function ElasticEase(oscillations, springiness) {
  29254. if (oscillations === void 0) { oscillations = 3; }
  29255. if (springiness === void 0) { springiness = 3; }
  29256. var _this = _super.call(this) || this;
  29257. _this.oscillations = oscillations;
  29258. _this.springiness = springiness;
  29259. return _this;
  29260. }
  29261. ElasticEase.prototype.easeInCore = function (gradient) {
  29262. var num2;
  29263. var num3 = Math.max(0.0, this.oscillations);
  29264. var num = Math.max(0.0, this.springiness);
  29265. if (num == 0) {
  29266. num2 = gradient;
  29267. }
  29268. else {
  29269. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  29270. }
  29271. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  29272. };
  29273. return ElasticEase;
  29274. }(EasingFunction));
  29275. BABYLON.ElasticEase = ElasticEase;
  29276. var ExponentialEase = (function (_super) {
  29277. __extends(ExponentialEase, _super);
  29278. function ExponentialEase(exponent) {
  29279. if (exponent === void 0) { exponent = 2; }
  29280. var _this = _super.call(this) || this;
  29281. _this.exponent = exponent;
  29282. return _this;
  29283. }
  29284. ExponentialEase.prototype.easeInCore = function (gradient) {
  29285. if (this.exponent <= 0) {
  29286. return gradient;
  29287. }
  29288. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  29289. };
  29290. return ExponentialEase;
  29291. }(EasingFunction));
  29292. BABYLON.ExponentialEase = ExponentialEase;
  29293. var PowerEase = (function (_super) {
  29294. __extends(PowerEase, _super);
  29295. function PowerEase(power) {
  29296. if (power === void 0) { power = 2; }
  29297. var _this = _super.call(this) || this;
  29298. _this.power = power;
  29299. return _this;
  29300. }
  29301. PowerEase.prototype.easeInCore = function (gradient) {
  29302. var y = Math.max(0.0, this.power);
  29303. return Math.pow(gradient, y);
  29304. };
  29305. return PowerEase;
  29306. }(EasingFunction));
  29307. BABYLON.PowerEase = PowerEase;
  29308. var QuadraticEase = (function (_super) {
  29309. __extends(QuadraticEase, _super);
  29310. function QuadraticEase() {
  29311. return _super !== null && _super.apply(this, arguments) || this;
  29312. }
  29313. QuadraticEase.prototype.easeInCore = function (gradient) {
  29314. return (gradient * gradient);
  29315. };
  29316. return QuadraticEase;
  29317. }(EasingFunction));
  29318. BABYLON.QuadraticEase = QuadraticEase;
  29319. var QuarticEase = (function (_super) {
  29320. __extends(QuarticEase, _super);
  29321. function QuarticEase() {
  29322. return _super !== null && _super.apply(this, arguments) || this;
  29323. }
  29324. QuarticEase.prototype.easeInCore = function (gradient) {
  29325. return (gradient * gradient * gradient * gradient);
  29326. };
  29327. return QuarticEase;
  29328. }(EasingFunction));
  29329. BABYLON.QuarticEase = QuarticEase;
  29330. var QuinticEase = (function (_super) {
  29331. __extends(QuinticEase, _super);
  29332. function QuinticEase() {
  29333. return _super !== null && _super.apply(this, arguments) || this;
  29334. }
  29335. QuinticEase.prototype.easeInCore = function (gradient) {
  29336. return (gradient * gradient * gradient * gradient * gradient);
  29337. };
  29338. return QuinticEase;
  29339. }(EasingFunction));
  29340. BABYLON.QuinticEase = QuinticEase;
  29341. var SineEase = (function (_super) {
  29342. __extends(SineEase, _super);
  29343. function SineEase() {
  29344. return _super !== null && _super.apply(this, arguments) || this;
  29345. }
  29346. SineEase.prototype.easeInCore = function (gradient) {
  29347. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  29348. };
  29349. return SineEase;
  29350. }(EasingFunction));
  29351. BABYLON.SineEase = SineEase;
  29352. var BezierCurveEase = (function (_super) {
  29353. __extends(BezierCurveEase, _super);
  29354. function BezierCurveEase(x1, y1, x2, y2) {
  29355. if (x1 === void 0) { x1 = 0; }
  29356. if (y1 === void 0) { y1 = 0; }
  29357. if (x2 === void 0) { x2 = 1; }
  29358. if (y2 === void 0) { y2 = 1; }
  29359. var _this = _super.call(this) || this;
  29360. _this.x1 = x1;
  29361. _this.y1 = y1;
  29362. _this.x2 = x2;
  29363. _this.y2 = y2;
  29364. return _this;
  29365. }
  29366. BezierCurveEase.prototype.easeInCore = function (gradient) {
  29367. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  29368. };
  29369. return BezierCurveEase;
  29370. }(EasingFunction));
  29371. BABYLON.BezierCurveEase = BezierCurveEase;
  29372. })(BABYLON || (BABYLON = {}));
  29373. //# sourceMappingURL=babylon.easing.js.map
  29374. var BABYLON;
  29375. (function (BABYLON) {
  29376. BABYLON.CameraInputTypes = {};
  29377. var CameraInputsManager = (function () {
  29378. function CameraInputsManager(camera) {
  29379. this.attached = {};
  29380. this.camera = camera;
  29381. this.checkInputs = function () { };
  29382. }
  29383. CameraInputsManager.prototype.add = function (input) {
  29384. var type = input.getSimpleName();
  29385. if (this.attached[type]) {
  29386. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  29387. return;
  29388. }
  29389. this.attached[type] = input;
  29390. input.camera = this.camera;
  29391. //for checkInputs, we are dynamically creating a function
  29392. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  29393. if (input.checkInputs) {
  29394. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  29395. }
  29396. if (this.attachedElement) {
  29397. input.attachControl(this.attachedElement);
  29398. }
  29399. };
  29400. CameraInputsManager.prototype.remove = function (inputToRemove) {
  29401. for (var cam in this.attached) {
  29402. var input = this.attached[cam];
  29403. if (input === inputToRemove) {
  29404. input.detachControl(this.attachedElement);
  29405. delete this.attached[cam];
  29406. this.rebuildInputCheck();
  29407. }
  29408. }
  29409. };
  29410. CameraInputsManager.prototype.removeByType = function (inputType) {
  29411. for (var cam in this.attached) {
  29412. var input = this.attached[cam];
  29413. if (input.getTypeName() === inputType) {
  29414. input.detachControl(this.attachedElement);
  29415. delete this.attached[cam];
  29416. this.rebuildInputCheck();
  29417. }
  29418. }
  29419. };
  29420. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  29421. var current = this.checkInputs;
  29422. return function () {
  29423. current();
  29424. fn();
  29425. };
  29426. };
  29427. CameraInputsManager.prototype.attachInput = function (input) {
  29428. input.attachControl(this.attachedElement, this.noPreventDefault);
  29429. };
  29430. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  29431. if (this.attachedElement) {
  29432. return;
  29433. }
  29434. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  29435. this.attachedElement = element;
  29436. this.noPreventDefault = noPreventDefault;
  29437. for (var cam in this.attached) {
  29438. var input = this.attached[cam];
  29439. this.attached[cam].attachControl(element, noPreventDefault);
  29440. }
  29441. };
  29442. CameraInputsManager.prototype.detachElement = function (element) {
  29443. if (this.attachedElement !== element) {
  29444. return;
  29445. }
  29446. for (var cam in this.attached) {
  29447. var input = this.attached[cam];
  29448. this.attached[cam].detachControl(element);
  29449. }
  29450. this.attachedElement = null;
  29451. };
  29452. CameraInputsManager.prototype.rebuildInputCheck = function () {
  29453. this.checkInputs = function () { };
  29454. for (var cam in this.attached) {
  29455. var input = this.attached[cam];
  29456. if (input.checkInputs) {
  29457. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  29458. }
  29459. }
  29460. };
  29461. CameraInputsManager.prototype.clear = function () {
  29462. if (this.attachedElement) {
  29463. this.detachElement(this.attachedElement);
  29464. }
  29465. this.attached = {};
  29466. this.attachedElement = null;
  29467. this.checkInputs = function () { };
  29468. };
  29469. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  29470. var inputs = {};
  29471. for (var cam in this.attached) {
  29472. var input = this.attached[cam];
  29473. var res = BABYLON.SerializationHelper.Serialize(input);
  29474. inputs[input.getTypeName()] = res;
  29475. }
  29476. serializedCamera.inputsmgr = inputs;
  29477. };
  29478. CameraInputsManager.prototype.parse = function (parsedCamera) {
  29479. var parsedInputs = parsedCamera.inputsmgr;
  29480. if (parsedInputs) {
  29481. this.clear();
  29482. for (var n in parsedInputs) {
  29483. var construct = BABYLON.CameraInputTypes[n];
  29484. if (construct) {
  29485. var parsedinput = parsedInputs[n];
  29486. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  29487. this.add(input);
  29488. }
  29489. }
  29490. }
  29491. else {
  29492. //2016-03-08 this part is for managing backward compatibility
  29493. for (var n in this.attached) {
  29494. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  29495. if (construct) {
  29496. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  29497. this.remove(this.attached[n]);
  29498. this.add(input);
  29499. }
  29500. }
  29501. }
  29502. };
  29503. return CameraInputsManager;
  29504. }());
  29505. BABYLON.CameraInputsManager = CameraInputsManager;
  29506. })(BABYLON || (BABYLON = {}));
  29507. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  29508. /// <reference path="babylon.camera.ts" />
  29509. var BABYLON;
  29510. (function (BABYLON) {
  29511. var TargetCamera = (function (_super) {
  29512. __extends(TargetCamera, _super);
  29513. function TargetCamera(name, position, scene) {
  29514. var _this = _super.call(this, name, position, scene) || this;
  29515. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  29516. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  29517. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  29518. _this.speed = 2.0;
  29519. _this.noRotationConstraint = false;
  29520. _this.lockedTarget = null;
  29521. _this._currentTarget = BABYLON.Vector3.Zero();
  29522. _this._viewMatrix = BABYLON.Matrix.Zero();
  29523. _this._camMatrix = BABYLON.Matrix.Zero();
  29524. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  29525. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  29526. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  29527. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  29528. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  29529. _this._lookAtTemp = BABYLON.Matrix.Zero();
  29530. _this._tempMatrix = BABYLON.Matrix.Zero();
  29531. return _this;
  29532. }
  29533. TargetCamera.prototype.getFrontPosition = function (distance) {
  29534. var direction = this.getTarget().subtract(this.position);
  29535. direction.normalize();
  29536. direction.scaleInPlace(distance);
  29537. return this.globalPosition.add(direction);
  29538. };
  29539. TargetCamera.prototype._getLockedTargetPosition = function () {
  29540. if (!this.lockedTarget) {
  29541. return null;
  29542. }
  29543. if (this.lockedTarget.absolutePosition) {
  29544. this.lockedTarget.computeWorldMatrix();
  29545. }
  29546. return this.lockedTarget.absolutePosition || this.lockedTarget;
  29547. };
  29548. // Cache
  29549. TargetCamera.prototype._initCache = function () {
  29550. _super.prototype._initCache.call(this);
  29551. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29552. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29553. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29554. };
  29555. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  29556. if (!ignoreParentClass) {
  29557. _super.prototype._updateCache.call(this);
  29558. }
  29559. var lockedTargetPosition = this._getLockedTargetPosition();
  29560. if (!lockedTargetPosition) {
  29561. this._cache.lockedTarget = null;
  29562. }
  29563. else {
  29564. if (!this._cache.lockedTarget) {
  29565. this._cache.lockedTarget = lockedTargetPosition.clone();
  29566. }
  29567. else {
  29568. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  29569. }
  29570. }
  29571. this._cache.rotation.copyFrom(this.rotation);
  29572. if (this.rotationQuaternion)
  29573. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  29574. };
  29575. // Synchronized
  29576. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  29577. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  29578. return false;
  29579. }
  29580. var lockedTargetPosition = this._getLockedTargetPosition();
  29581. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  29582. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  29583. };
  29584. // Methods
  29585. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  29586. var engine = this.getEngine();
  29587. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  29588. };
  29589. // Target
  29590. TargetCamera.prototype.setTarget = function (target) {
  29591. this.upVector.normalize();
  29592. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  29593. this._camMatrix.invert();
  29594. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  29595. var vDir = target.subtract(this.position);
  29596. if (vDir.x >= 0.0) {
  29597. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  29598. }
  29599. else {
  29600. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  29601. }
  29602. this.rotation.z = 0;
  29603. if (isNaN(this.rotation.x)) {
  29604. this.rotation.x = 0;
  29605. }
  29606. if (isNaN(this.rotation.y)) {
  29607. this.rotation.y = 0;
  29608. }
  29609. if (isNaN(this.rotation.z)) {
  29610. this.rotation.z = 0;
  29611. }
  29612. if (this.rotationQuaternion) {
  29613. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  29614. }
  29615. };
  29616. /**
  29617. * Return the current target position of the camera. This value is expressed in local space.
  29618. */
  29619. TargetCamera.prototype.getTarget = function () {
  29620. return this._currentTarget;
  29621. };
  29622. TargetCamera.prototype._decideIfNeedsToMove = function () {
  29623. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  29624. };
  29625. TargetCamera.prototype._updatePosition = function () {
  29626. if (this.parent) {
  29627. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  29628. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  29629. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  29630. return;
  29631. }
  29632. this.position.addInPlace(this.cameraDirection);
  29633. };
  29634. TargetCamera.prototype._checkInputs = function () {
  29635. var needToMove = this._decideIfNeedsToMove();
  29636. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  29637. // Move
  29638. if (needToMove) {
  29639. this._updatePosition();
  29640. }
  29641. // Rotate
  29642. if (needToRotate) {
  29643. this.rotation.x += this.cameraRotation.x;
  29644. this.rotation.y += this.cameraRotation.y;
  29645. //rotate, if quaternion is set and rotation was used
  29646. if (this.rotationQuaternion) {
  29647. var len = this.rotation.lengthSquared();
  29648. if (len) {
  29649. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  29650. }
  29651. }
  29652. if (!this.noRotationConstraint) {
  29653. var limit = (Math.PI / 2) * 0.95;
  29654. if (this.rotation.x > limit)
  29655. this.rotation.x = limit;
  29656. if (this.rotation.x < -limit)
  29657. this.rotation.x = -limit;
  29658. }
  29659. }
  29660. // Inertia
  29661. if (needToMove) {
  29662. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  29663. this.cameraDirection.x = 0;
  29664. }
  29665. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  29666. this.cameraDirection.y = 0;
  29667. }
  29668. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  29669. this.cameraDirection.z = 0;
  29670. }
  29671. this.cameraDirection.scaleInPlace(this.inertia);
  29672. }
  29673. if (needToRotate) {
  29674. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  29675. this.cameraRotation.x = 0;
  29676. }
  29677. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  29678. this.cameraRotation.y = 0;
  29679. }
  29680. this.cameraRotation.scaleInPlace(this.inertia);
  29681. }
  29682. _super.prototype._checkInputs.call(this);
  29683. };
  29684. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  29685. if (this.rotationQuaternion) {
  29686. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  29687. //update the up vector!
  29688. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  29689. }
  29690. else {
  29691. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  29692. }
  29693. };
  29694. TargetCamera.prototype._getViewMatrix = function () {
  29695. if (!this.lockedTarget) {
  29696. // Compute
  29697. this._updateCameraRotationMatrix();
  29698. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  29699. // Computing target and final matrix
  29700. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  29701. }
  29702. else {
  29703. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  29704. }
  29705. if (this.getScene().useRightHandedSystem) {
  29706. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  29707. }
  29708. else {
  29709. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  29710. }
  29711. return this._viewMatrix;
  29712. };
  29713. /**
  29714. * @override
  29715. * Override Camera.createRigCamera
  29716. */
  29717. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  29718. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  29719. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  29720. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  29721. if (!this.rotationQuaternion) {
  29722. this.rotationQuaternion = new BABYLON.Quaternion();
  29723. }
  29724. rigCamera._cameraRigParams = {};
  29725. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  29726. }
  29727. return rigCamera;
  29728. }
  29729. return null;
  29730. };
  29731. /**
  29732. * @override
  29733. * Override Camera._updateRigCameras
  29734. */
  29735. TargetCamera.prototype._updateRigCameras = function () {
  29736. var camLeft = this._rigCameras[0];
  29737. var camRight = this._rigCameras[1];
  29738. switch (this.cameraRigMode) {
  29739. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  29740. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  29741. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  29742. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  29743. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  29744. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  29745. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  29746. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  29747. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  29748. camLeft.setTarget(this.getTarget());
  29749. camRight.setTarget(this.getTarget());
  29750. break;
  29751. case BABYLON.Camera.RIG_MODE_VR:
  29752. if (camLeft.rotationQuaternion) {
  29753. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  29754. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  29755. }
  29756. else {
  29757. camLeft.rotation.copyFrom(this.rotation);
  29758. camRight.rotation.copyFrom(this.rotation);
  29759. }
  29760. camLeft.position.copyFrom(this.position);
  29761. camRight.position.copyFrom(this.position);
  29762. break;
  29763. }
  29764. _super.prototype._updateRigCameras.call(this);
  29765. };
  29766. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  29767. if (!this._rigCamTransformMatrix) {
  29768. this._rigCamTransformMatrix = new BABYLON.Matrix();
  29769. }
  29770. var target = this.getTarget();
  29771. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  29772. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  29773. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  29774. };
  29775. TargetCamera.prototype.getClassName = function () {
  29776. return "TargetCamera";
  29777. };
  29778. return TargetCamera;
  29779. }(BABYLON.Camera));
  29780. __decorate([
  29781. BABYLON.serializeAsVector3()
  29782. ], TargetCamera.prototype, "rotation", void 0);
  29783. __decorate([
  29784. BABYLON.serialize()
  29785. ], TargetCamera.prototype, "speed", void 0);
  29786. __decorate([
  29787. BABYLON.serializeAsMeshReference("lockedTargetId")
  29788. ], TargetCamera.prototype, "lockedTarget", void 0);
  29789. BABYLON.TargetCamera = TargetCamera;
  29790. })(BABYLON || (BABYLON = {}));
  29791. //# sourceMappingURL=babylon.targetCamera.js.map
  29792. var BABYLON;
  29793. (function (BABYLON) {
  29794. var ArcRotateCameraKeyboardMoveInput = (function () {
  29795. function ArcRotateCameraKeyboardMoveInput() {
  29796. this._keys = [];
  29797. this.keysUp = [38];
  29798. this.keysDown = [40];
  29799. this.keysLeft = [37];
  29800. this.keysRight = [39];
  29801. }
  29802. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  29803. var _this = this;
  29804. element.tabIndex = 1;
  29805. this._onKeyDown = function (evt) {
  29806. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  29807. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  29808. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  29809. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  29810. var index = _this._keys.indexOf(evt.keyCode);
  29811. if (index === -1) {
  29812. _this._keys.push(evt.keyCode);
  29813. }
  29814. if (evt.preventDefault) {
  29815. if (!noPreventDefault) {
  29816. evt.preventDefault();
  29817. }
  29818. }
  29819. }
  29820. };
  29821. this._onKeyUp = function (evt) {
  29822. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  29823. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  29824. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  29825. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  29826. var index = _this._keys.indexOf(evt.keyCode);
  29827. if (index >= 0) {
  29828. _this._keys.splice(index, 1);
  29829. }
  29830. if (evt.preventDefault) {
  29831. if (!noPreventDefault) {
  29832. evt.preventDefault();
  29833. }
  29834. }
  29835. }
  29836. };
  29837. this._onLostFocus = function () {
  29838. _this._keys = [];
  29839. };
  29840. element.addEventListener("keydown", this._onKeyDown, false);
  29841. element.addEventListener("keyup", this._onKeyUp, false);
  29842. BABYLON.Tools.RegisterTopRootEvents([
  29843. { name: "blur", handler: this._onLostFocus }
  29844. ]);
  29845. };
  29846. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  29847. if (element) {
  29848. element.removeEventListener("keydown", this._onKeyDown);
  29849. element.removeEventListener("keyup", this._onKeyUp);
  29850. }
  29851. BABYLON.Tools.UnregisterTopRootEvents([
  29852. { name: "blur", handler: this._onLostFocus }
  29853. ]);
  29854. this._keys = [];
  29855. this._onKeyDown = null;
  29856. this._onKeyUp = null;
  29857. this._onLostFocus = null;
  29858. };
  29859. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  29860. if (this._onKeyDown) {
  29861. var camera = this.camera;
  29862. for (var index = 0; index < this._keys.length; index++) {
  29863. var keyCode = this._keys[index];
  29864. if (this.keysLeft.indexOf(keyCode) !== -1) {
  29865. camera.inertialAlphaOffset -= 0.01;
  29866. }
  29867. else if (this.keysUp.indexOf(keyCode) !== -1) {
  29868. camera.inertialBetaOffset -= 0.01;
  29869. }
  29870. else if (this.keysRight.indexOf(keyCode) !== -1) {
  29871. camera.inertialAlphaOffset += 0.01;
  29872. }
  29873. else if (this.keysDown.indexOf(keyCode) !== -1) {
  29874. camera.inertialBetaOffset += 0.01;
  29875. }
  29876. }
  29877. }
  29878. };
  29879. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  29880. return "ArcRotateCameraKeyboardMoveInput";
  29881. };
  29882. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  29883. return "keyboard";
  29884. };
  29885. return ArcRotateCameraKeyboardMoveInput;
  29886. }());
  29887. __decorate([
  29888. BABYLON.serialize()
  29889. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  29890. __decorate([
  29891. BABYLON.serialize()
  29892. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  29893. __decorate([
  29894. BABYLON.serialize()
  29895. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  29896. __decorate([
  29897. BABYLON.serialize()
  29898. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  29899. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  29900. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  29901. })(BABYLON || (BABYLON = {}));
  29902. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  29903. var BABYLON;
  29904. (function (BABYLON) {
  29905. var ArcRotateCameraMouseWheelInput = (function () {
  29906. function ArcRotateCameraMouseWheelInput() {
  29907. this.wheelPrecision = 3.0;
  29908. }
  29909. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  29910. var _this = this;
  29911. this._wheel = function (p, s) {
  29912. //sanity check - this should be a PointerWheel event.
  29913. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  29914. return;
  29915. var event = p.event;
  29916. var delta = 0;
  29917. if (event.wheelDelta) {
  29918. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  29919. }
  29920. else if (event.detail) {
  29921. delta = -event.detail / _this.wheelPrecision;
  29922. }
  29923. if (delta)
  29924. _this.camera.inertialRadiusOffset += delta;
  29925. if (event.preventDefault) {
  29926. if (!noPreventDefault) {
  29927. event.preventDefault();
  29928. }
  29929. }
  29930. };
  29931. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  29932. };
  29933. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  29934. if (this._observer && element) {
  29935. this.camera.getScene().onPointerObservable.remove(this._observer);
  29936. this._observer = null;
  29937. this._wheel = null;
  29938. }
  29939. };
  29940. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  29941. return "ArcRotateCameraMouseWheelInput";
  29942. };
  29943. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  29944. return "mousewheel";
  29945. };
  29946. return ArcRotateCameraMouseWheelInput;
  29947. }());
  29948. __decorate([
  29949. BABYLON.serialize()
  29950. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  29951. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  29952. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  29953. })(BABYLON || (BABYLON = {}));
  29954. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  29955. var BABYLON;
  29956. (function (BABYLON) {
  29957. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  29958. var ArcRotateCameraPointersInput = (function () {
  29959. function ArcRotateCameraPointersInput() {
  29960. this.buttons = [0, 1, 2];
  29961. this.angularSensibilityX = 1000.0;
  29962. this.angularSensibilityY = 1000.0;
  29963. this.pinchPrecision = 6.0;
  29964. this.panningSensibility = 50.0;
  29965. this._isPanClick = false;
  29966. this.pinchInwards = true;
  29967. }
  29968. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  29969. var _this = this;
  29970. var engine = this.camera.getEngine();
  29971. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  29972. var pointA, pointB;
  29973. var previousPinchDistance = 0;
  29974. this._pointerInput = function (p, s) {
  29975. var evt = p.event;
  29976. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  29977. return;
  29978. }
  29979. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  29980. try {
  29981. evt.srcElement.setPointerCapture(evt.pointerId);
  29982. }
  29983. catch (e) {
  29984. //Nothing to do with the error. Execution will continue.
  29985. }
  29986. // Manage panning with pan button click
  29987. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  29988. // manage pointers
  29989. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  29990. if (pointA === undefined) {
  29991. pointA = cacheSoloPointer;
  29992. }
  29993. else if (pointB === undefined) {
  29994. pointB = cacheSoloPointer;
  29995. }
  29996. if (!noPreventDefault) {
  29997. evt.preventDefault();
  29998. element.focus();
  29999. }
  30000. }
  30001. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  30002. try {
  30003. evt.srcElement.releasePointerCapture(evt.pointerId);
  30004. }
  30005. catch (e) {
  30006. //Nothing to do with the error.
  30007. }
  30008. cacheSoloPointer = null;
  30009. previousPinchDistance = 0;
  30010. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  30011. //but emptying completly pointers collection is required to fix a bug on iPhone :
  30012. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  30013. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  30014. pointA = pointB = undefined;
  30015. if (!noPreventDefault) {
  30016. evt.preventDefault();
  30017. }
  30018. }
  30019. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  30020. if (!noPreventDefault) {
  30021. evt.preventDefault();
  30022. }
  30023. // One button down
  30024. if (pointA && pointB === undefined) {
  30025. if (_this.panningSensibility !== 0 &&
  30026. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  30027. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  30028. _this.camera
  30029. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  30030. _this.camera
  30031. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  30032. }
  30033. else {
  30034. var offsetX = evt.clientX - cacheSoloPointer.x;
  30035. var offsetY = evt.clientY - cacheSoloPointer.y;
  30036. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  30037. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  30038. }
  30039. cacheSoloPointer.x = evt.clientX;
  30040. cacheSoloPointer.y = evt.clientY;
  30041. }
  30042. else if (pointA && pointB) {
  30043. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  30044. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  30045. ed.x = evt.clientX;
  30046. ed.y = evt.clientY;
  30047. var direction = _this.pinchInwards ? 1 : -1;
  30048. var distX = pointA.x - pointB.x;
  30049. var distY = pointA.y - pointB.y;
  30050. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  30051. if (previousPinchDistance === 0) {
  30052. previousPinchDistance = pinchSquaredDistance;
  30053. return;
  30054. }
  30055. if (pinchSquaredDistance !== previousPinchDistance) {
  30056. _this.camera
  30057. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  30058. (_this.pinchPrecision *
  30059. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  30060. direction);
  30061. previousPinchDistance = pinchSquaredDistance;
  30062. }
  30063. }
  30064. }
  30065. };
  30066. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  30067. this._onContextMenu = function (evt) {
  30068. evt.preventDefault();
  30069. };
  30070. if (!this.camera._useCtrlForPanning) {
  30071. element.addEventListener("contextmenu", this._onContextMenu, false);
  30072. }
  30073. this._onLostFocus = function () {
  30074. //this._keys = [];
  30075. pointA = pointB = undefined;
  30076. previousPinchDistance = 0;
  30077. cacheSoloPointer = null;
  30078. };
  30079. this._onMouseMove = function (evt) {
  30080. if (!engine.isPointerLock) {
  30081. return;
  30082. }
  30083. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  30084. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  30085. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  30086. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  30087. if (!noPreventDefault) {
  30088. evt.preventDefault();
  30089. }
  30090. };
  30091. this._onGestureStart = function (e) {
  30092. if (window.MSGesture === undefined) {
  30093. return;
  30094. }
  30095. if (!_this._MSGestureHandler) {
  30096. _this._MSGestureHandler = new MSGesture();
  30097. _this._MSGestureHandler.target = element;
  30098. }
  30099. _this._MSGestureHandler.addPointer(e.pointerId);
  30100. };
  30101. this._onGesture = function (e) {
  30102. _this.camera.radius *= e.scale;
  30103. if (e.preventDefault) {
  30104. if (!noPreventDefault) {
  30105. e.stopPropagation();
  30106. e.preventDefault();
  30107. }
  30108. }
  30109. };
  30110. element.addEventListener("mousemove", this._onMouseMove, false);
  30111. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  30112. element.addEventListener("MSGestureChange", this._onGesture, false);
  30113. BABYLON.Tools.RegisterTopRootEvents([
  30114. { name: "blur", handler: this._onLostFocus }
  30115. ]);
  30116. };
  30117. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  30118. if (element && this._observer) {
  30119. this.camera.getScene().onPointerObservable.remove(this._observer);
  30120. this._observer = null;
  30121. element.removeEventListener("contextmenu", this._onContextMenu);
  30122. element.removeEventListener("mousemove", this._onMouseMove);
  30123. element.removeEventListener("MSPointerDown", this._onGestureStart);
  30124. element.removeEventListener("MSGestureChange", this._onGesture);
  30125. this._isPanClick = false;
  30126. this.pinchInwards = true;
  30127. this._onMouseMove = null;
  30128. this._onGestureStart = null;
  30129. this._onGesture = null;
  30130. this._MSGestureHandler = null;
  30131. this._onLostFocus = null;
  30132. this._onContextMenu = null;
  30133. }
  30134. BABYLON.Tools.UnregisterTopRootEvents([
  30135. { name: "blur", handler: this._onLostFocus }
  30136. ]);
  30137. };
  30138. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  30139. return "ArcRotateCameraPointersInput";
  30140. };
  30141. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  30142. return "pointers";
  30143. };
  30144. return ArcRotateCameraPointersInput;
  30145. }());
  30146. __decorate([
  30147. BABYLON.serialize()
  30148. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  30149. __decorate([
  30150. BABYLON.serialize()
  30151. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  30152. __decorate([
  30153. BABYLON.serialize()
  30154. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  30155. __decorate([
  30156. BABYLON.serialize()
  30157. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  30158. __decorate([
  30159. BABYLON.serialize()
  30160. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  30161. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  30162. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  30163. })(BABYLON || (BABYLON = {}));
  30164. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  30165. /// <reference path="babylon.targetCamera.ts" />
  30166. /// <reference path="..\Tools\babylon.tools.ts" />
  30167. var BABYLON;
  30168. (function (BABYLON) {
  30169. var ArcRotateCamera = (function (_super) {
  30170. __extends(ArcRotateCamera, _super);
  30171. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  30172. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  30173. _this.inertialAlphaOffset = 0;
  30174. _this.inertialBetaOffset = 0;
  30175. _this.inertialRadiusOffset = 0;
  30176. _this.lowerAlphaLimit = null;
  30177. _this.upperAlphaLimit = null;
  30178. _this.lowerBetaLimit = 0.01;
  30179. _this.upperBetaLimit = Math.PI;
  30180. _this.lowerRadiusLimit = null;
  30181. _this.upperRadiusLimit = null;
  30182. _this.inertialPanningX = 0;
  30183. _this.inertialPanningY = 0;
  30184. _this.panningInertia = 0.9;
  30185. //-- end properties for backward compatibility for inputs
  30186. _this.zoomOnFactor = 1;
  30187. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  30188. _this.allowUpsideDown = true;
  30189. _this._viewMatrix = new BABYLON.Matrix();
  30190. // Panning
  30191. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  30192. _this.checkCollisions = false;
  30193. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  30194. _this._previousPosition = BABYLON.Vector3.Zero();
  30195. _this._collisionVelocity = BABYLON.Vector3.Zero();
  30196. _this._newPosition = BABYLON.Vector3.Zero();
  30197. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  30198. if (collidedMesh === void 0) { collidedMesh = null; }
  30199. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  30200. newPosition.multiplyInPlace(_this._collider.radius);
  30201. }
  30202. if (!collidedMesh) {
  30203. _this._previousPosition.copyFrom(_this.position);
  30204. }
  30205. else {
  30206. _this.setPosition(newPosition);
  30207. if (_this.onCollide) {
  30208. _this.onCollide(collidedMesh);
  30209. }
  30210. }
  30211. // Recompute because of constraints
  30212. var cosa = Math.cos(_this.alpha);
  30213. var sina = Math.sin(_this.alpha);
  30214. var cosb = Math.cos(_this.beta);
  30215. var sinb = Math.sin(_this.beta);
  30216. if (sinb === 0) {
  30217. sinb = 0.0001;
  30218. }
  30219. var target = _this._getTargetPosition();
  30220. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  30221. _this.position.copyFrom(_this._newPosition);
  30222. var up = _this.upVector;
  30223. if (_this.allowUpsideDown && _this.beta < 0) {
  30224. up = up.clone();
  30225. up = up.negate();
  30226. }
  30227. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  30228. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  30229. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  30230. _this._collisionTriggered = false;
  30231. };
  30232. _this._target = BABYLON.Vector3.Zero();
  30233. if (target) {
  30234. _this.setTarget(target);
  30235. }
  30236. _this.alpha = alpha;
  30237. _this.beta = beta;
  30238. _this.radius = radius;
  30239. _this.getViewMatrix();
  30240. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  30241. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  30242. return _this;
  30243. }
  30244. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  30245. get: function () {
  30246. return this._target;
  30247. },
  30248. set: function (value) {
  30249. this.setTarget(value);
  30250. },
  30251. enumerable: true,
  30252. configurable: true
  30253. });
  30254. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  30255. //-- begin properties for backward compatibility for inputs
  30256. get: function () {
  30257. var pointers = this.inputs.attached["pointers"];
  30258. if (pointers)
  30259. return pointers.angularSensibilityX;
  30260. },
  30261. set: function (value) {
  30262. var pointers = this.inputs.attached["pointers"];
  30263. if (pointers) {
  30264. pointers.angularSensibilityX = value;
  30265. }
  30266. },
  30267. enumerable: true,
  30268. configurable: true
  30269. });
  30270. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  30271. get: function () {
  30272. var pointers = this.inputs.attached["pointers"];
  30273. if (pointers)
  30274. return pointers.angularSensibilityY;
  30275. },
  30276. set: function (value) {
  30277. var pointers = this.inputs.attached["pointers"];
  30278. if (pointers) {
  30279. pointers.angularSensibilityY = value;
  30280. }
  30281. },
  30282. enumerable: true,
  30283. configurable: true
  30284. });
  30285. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  30286. get: function () {
  30287. var pointers = this.inputs.attached["pointers"];
  30288. if (pointers)
  30289. return pointers.pinchPrecision;
  30290. },
  30291. set: function (value) {
  30292. var pointers = this.inputs.attached["pointers"];
  30293. if (pointers) {
  30294. pointers.pinchPrecision = value;
  30295. }
  30296. },
  30297. enumerable: true,
  30298. configurable: true
  30299. });
  30300. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  30301. get: function () {
  30302. var pointers = this.inputs.attached["pointers"];
  30303. if (pointers)
  30304. return pointers.panningSensibility;
  30305. },
  30306. set: function (value) {
  30307. var pointers = this.inputs.attached["pointers"];
  30308. if (pointers) {
  30309. pointers.panningSensibility = value;
  30310. }
  30311. },
  30312. enumerable: true,
  30313. configurable: true
  30314. });
  30315. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  30316. get: function () {
  30317. var keyboard = this.inputs.attached["keyboard"];
  30318. if (keyboard)
  30319. return keyboard.keysUp;
  30320. },
  30321. set: function (value) {
  30322. var keyboard = this.inputs.attached["keyboard"];
  30323. if (keyboard)
  30324. keyboard.keysUp = value;
  30325. },
  30326. enumerable: true,
  30327. configurable: true
  30328. });
  30329. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  30330. get: function () {
  30331. var keyboard = this.inputs.attached["keyboard"];
  30332. if (keyboard)
  30333. return keyboard.keysDown;
  30334. },
  30335. set: function (value) {
  30336. var keyboard = this.inputs.attached["keyboard"];
  30337. if (keyboard)
  30338. keyboard.keysDown = value;
  30339. },
  30340. enumerable: true,
  30341. configurable: true
  30342. });
  30343. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  30344. get: function () {
  30345. var keyboard = this.inputs.attached["keyboard"];
  30346. if (keyboard)
  30347. return keyboard.keysLeft;
  30348. },
  30349. set: function (value) {
  30350. var keyboard = this.inputs.attached["keyboard"];
  30351. if (keyboard)
  30352. keyboard.keysLeft = value;
  30353. },
  30354. enumerable: true,
  30355. configurable: true
  30356. });
  30357. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  30358. get: function () {
  30359. var keyboard = this.inputs.attached["keyboard"];
  30360. if (keyboard)
  30361. return keyboard.keysRight;
  30362. },
  30363. set: function (value) {
  30364. var keyboard = this.inputs.attached["keyboard"];
  30365. if (keyboard)
  30366. keyboard.keysRight = value;
  30367. },
  30368. enumerable: true,
  30369. configurable: true
  30370. });
  30371. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  30372. get: function () {
  30373. var mousewheel = this.inputs.attached["mousewheel"];
  30374. if (mousewheel)
  30375. return mousewheel.wheelPrecision;
  30376. },
  30377. set: function (value) {
  30378. var mousewheel = this.inputs.attached["mousewheel"];
  30379. if (mousewheel)
  30380. mousewheel.wheelPrecision = value;
  30381. },
  30382. enumerable: true,
  30383. configurable: true
  30384. });
  30385. // Cache
  30386. ArcRotateCamera.prototype._initCache = function () {
  30387. _super.prototype._initCache.call(this);
  30388. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  30389. this._cache.alpha = undefined;
  30390. this._cache.beta = undefined;
  30391. this._cache.radius = undefined;
  30392. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  30393. };
  30394. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  30395. if (!ignoreParentClass) {
  30396. _super.prototype._updateCache.call(this);
  30397. }
  30398. this._cache._target.copyFrom(this._getTargetPosition());
  30399. this._cache.alpha = this.alpha;
  30400. this._cache.beta = this.beta;
  30401. this._cache.radius = this.radius;
  30402. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  30403. };
  30404. ArcRotateCamera.prototype._getTargetPosition = function () {
  30405. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  30406. var pos = this._targetHost.getAbsolutePosition();
  30407. if (this._targetBoundingCenter) {
  30408. pos.addToRef(this._targetBoundingCenter, this._target);
  30409. }
  30410. else {
  30411. this._target.copyFrom(pos);
  30412. }
  30413. }
  30414. return this._target;
  30415. };
  30416. // Synchronized
  30417. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  30418. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  30419. return false;
  30420. return this._cache._target.equals(this._getTargetPosition())
  30421. && this._cache.alpha === this.alpha
  30422. && this._cache.beta === this.beta
  30423. && this._cache.radius === this.radius
  30424. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  30425. };
  30426. // Methods
  30427. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  30428. var _this = this;
  30429. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  30430. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  30431. this._useCtrlForPanning = useCtrlForPanning;
  30432. this._panningMouseButton = panningMouseButton;
  30433. this.inputs.attachElement(element, noPreventDefault);
  30434. this._reset = function () {
  30435. _this.inertialAlphaOffset = 0;
  30436. _this.inertialBetaOffset = 0;
  30437. _this.inertialRadiusOffset = 0;
  30438. };
  30439. };
  30440. ArcRotateCamera.prototype.detachControl = function (element) {
  30441. this.inputs.detachElement(element);
  30442. if (this._reset) {
  30443. this._reset();
  30444. }
  30445. };
  30446. ArcRotateCamera.prototype._checkInputs = function () {
  30447. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  30448. if (this._collisionTriggered) {
  30449. return;
  30450. }
  30451. this.inputs.checkInputs();
  30452. // Inertia
  30453. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  30454. if (this.getScene().useRightHandedSystem) {
  30455. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  30456. }
  30457. else {
  30458. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  30459. }
  30460. this.beta += this.inertialBetaOffset;
  30461. this.radius -= this.inertialRadiusOffset;
  30462. this.inertialAlphaOffset *= this.inertia;
  30463. this.inertialBetaOffset *= this.inertia;
  30464. this.inertialRadiusOffset *= this.inertia;
  30465. if (Math.abs(this.inertialAlphaOffset) < this.speed * BABYLON.Epsilon)
  30466. this.inertialAlphaOffset = 0;
  30467. if (Math.abs(this.inertialBetaOffset) < this.speed * BABYLON.Epsilon)
  30468. this.inertialBetaOffset = 0;
  30469. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  30470. this.inertialRadiusOffset = 0;
  30471. }
  30472. // Panning inertia
  30473. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  30474. if (!this._localDirection) {
  30475. this._localDirection = BABYLON.Vector3.Zero();
  30476. this._transformedDirection = BABYLON.Vector3.Zero();
  30477. }
  30478. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  30479. this._localDirection.multiplyInPlace(this.panningAxis);
  30480. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  30481. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  30482. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  30483. if (!this.panningAxis.y) {
  30484. this._transformedDirection.y = 0;
  30485. }
  30486. if (!this._targetHost) {
  30487. this._target.addInPlace(this._transformedDirection);
  30488. }
  30489. this.inertialPanningX *= this.panningInertia;
  30490. this.inertialPanningY *= this.panningInertia;
  30491. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  30492. this.inertialPanningX = 0;
  30493. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  30494. this.inertialPanningY = 0;
  30495. }
  30496. // Limits
  30497. this._checkLimits();
  30498. _super.prototype._checkInputs.call(this);
  30499. };
  30500. ArcRotateCamera.prototype._checkLimits = function () {
  30501. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  30502. if (this.allowUpsideDown && this.beta > Math.PI) {
  30503. this.beta = this.beta - (2 * Math.PI);
  30504. }
  30505. }
  30506. else {
  30507. if (this.beta < this.lowerBetaLimit) {
  30508. this.beta = this.lowerBetaLimit;
  30509. }
  30510. }
  30511. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  30512. if (this.allowUpsideDown && this.beta < -Math.PI) {
  30513. this.beta = this.beta + (2 * Math.PI);
  30514. }
  30515. }
  30516. else {
  30517. if (this.beta > this.upperBetaLimit) {
  30518. this.beta = this.upperBetaLimit;
  30519. }
  30520. }
  30521. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  30522. this.alpha = this.lowerAlphaLimit;
  30523. }
  30524. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  30525. this.alpha = this.upperAlphaLimit;
  30526. }
  30527. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  30528. this.radius = this.lowerRadiusLimit;
  30529. }
  30530. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  30531. this.radius = this.upperRadiusLimit;
  30532. }
  30533. };
  30534. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  30535. var radiusv3 = this.position.subtract(this._getTargetPosition());
  30536. this.radius = radiusv3.length();
  30537. // Alpha
  30538. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  30539. if (radiusv3.z < 0) {
  30540. this.alpha = 2 * Math.PI - this.alpha;
  30541. }
  30542. // Beta
  30543. this.beta = Math.acos(radiusv3.y / this.radius);
  30544. this._checkLimits();
  30545. };
  30546. ArcRotateCamera.prototype.setPosition = function (position) {
  30547. if (this.position.equals(position)) {
  30548. return;
  30549. }
  30550. this.position.copyFrom(position);
  30551. this.rebuildAnglesAndRadius();
  30552. };
  30553. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  30554. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  30555. if (allowSamePosition === void 0) { allowSamePosition = false; }
  30556. if (target.getBoundingInfo) {
  30557. if (toBoundingCenter) {
  30558. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  30559. }
  30560. else {
  30561. this._targetBoundingCenter = null;
  30562. }
  30563. this._targetHost = target;
  30564. this._target = this._getTargetPosition();
  30565. }
  30566. else {
  30567. var newTarget = target;
  30568. var currentTarget = this._getTargetPosition();
  30569. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  30570. return;
  30571. }
  30572. this._target = newTarget;
  30573. this._targetBoundingCenter = null;
  30574. }
  30575. this.rebuildAnglesAndRadius();
  30576. };
  30577. ArcRotateCamera.prototype._getViewMatrix = function () {
  30578. // Compute
  30579. var cosa = Math.cos(this.alpha);
  30580. var sina = Math.sin(this.alpha);
  30581. var cosb = Math.cos(this.beta);
  30582. var sinb = Math.sin(this.beta);
  30583. if (sinb === 0) {
  30584. sinb = 0.0001;
  30585. }
  30586. var target = this._getTargetPosition();
  30587. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  30588. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  30589. if (!this._collider) {
  30590. this._collider = new BABYLON.Collider();
  30591. }
  30592. this._collider.radius = this.collisionRadius;
  30593. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  30594. this._collisionTriggered = true;
  30595. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  30596. }
  30597. else {
  30598. this.position.copyFrom(this._newPosition);
  30599. var up = this.upVector;
  30600. if (this.allowUpsideDown && sinb < 0) {
  30601. up = up.clone();
  30602. up = up.negate();
  30603. }
  30604. if (this.getScene().useRightHandedSystem) {
  30605. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  30606. }
  30607. else {
  30608. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  30609. }
  30610. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  30611. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  30612. }
  30613. this._currentTarget = target;
  30614. return this._viewMatrix;
  30615. };
  30616. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  30617. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  30618. meshes = meshes || this.getScene().meshes;
  30619. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  30620. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  30621. this.radius = distance * this.zoomOnFactor;
  30622. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  30623. };
  30624. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  30625. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  30626. var meshesOrMinMaxVector;
  30627. var distance;
  30628. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  30629. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  30630. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  30631. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  30632. }
  30633. else {
  30634. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  30635. distance = meshesOrMinMaxVectorAndDistance.distance;
  30636. }
  30637. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  30638. if (!doNotUpdateMaxZ) {
  30639. this.maxZ = distance * 2;
  30640. }
  30641. };
  30642. /**
  30643. * @override
  30644. * Override Camera.createRigCamera
  30645. */
  30646. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  30647. var alphaShift;
  30648. switch (this.cameraRigMode) {
  30649. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  30650. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  30651. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  30652. case BABYLON.Camera.RIG_MODE_VR:
  30653. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  30654. break;
  30655. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  30656. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  30657. break;
  30658. }
  30659. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  30660. rigCam._cameraRigParams = {};
  30661. return rigCam;
  30662. };
  30663. /**
  30664. * @override
  30665. * Override Camera._updateRigCameras
  30666. */
  30667. ArcRotateCamera.prototype._updateRigCameras = function () {
  30668. var camLeft = this._rigCameras[0];
  30669. var camRight = this._rigCameras[1];
  30670. camLeft.beta = camRight.beta = this.beta;
  30671. camLeft.radius = camRight.radius = this.radius;
  30672. switch (this.cameraRigMode) {
  30673. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  30674. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  30675. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  30676. case BABYLON.Camera.RIG_MODE_VR:
  30677. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  30678. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  30679. break;
  30680. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  30681. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  30682. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  30683. break;
  30684. }
  30685. _super.prototype._updateRigCameras.call(this);
  30686. };
  30687. ArcRotateCamera.prototype.dispose = function () {
  30688. this.inputs.clear();
  30689. _super.prototype.dispose.call(this);
  30690. };
  30691. ArcRotateCamera.prototype.getClassName = function () {
  30692. return "ArcRotateCamera";
  30693. };
  30694. return ArcRotateCamera;
  30695. }(BABYLON.TargetCamera));
  30696. __decorate([
  30697. BABYLON.serialize()
  30698. ], ArcRotateCamera.prototype, "alpha", void 0);
  30699. __decorate([
  30700. BABYLON.serialize()
  30701. ], ArcRotateCamera.prototype, "beta", void 0);
  30702. __decorate([
  30703. BABYLON.serialize()
  30704. ], ArcRotateCamera.prototype, "radius", void 0);
  30705. __decorate([
  30706. BABYLON.serializeAsVector3("target")
  30707. ], ArcRotateCamera.prototype, "_target", void 0);
  30708. __decorate([
  30709. BABYLON.serialize()
  30710. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  30711. __decorate([
  30712. BABYLON.serialize()
  30713. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  30714. __decorate([
  30715. BABYLON.serialize()
  30716. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  30717. __decorate([
  30718. BABYLON.serialize()
  30719. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  30720. __decorate([
  30721. BABYLON.serialize()
  30722. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  30723. __decorate([
  30724. BABYLON.serialize()
  30725. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  30726. __decorate([
  30727. BABYLON.serialize()
  30728. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  30729. __decorate([
  30730. BABYLON.serialize()
  30731. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  30732. __decorate([
  30733. BABYLON.serialize()
  30734. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  30735. __decorate([
  30736. BABYLON.serialize()
  30737. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  30738. __decorate([
  30739. BABYLON.serialize()
  30740. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  30741. __decorate([
  30742. BABYLON.serialize()
  30743. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  30744. __decorate([
  30745. BABYLON.serialize()
  30746. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  30747. __decorate([
  30748. BABYLON.serialize()
  30749. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  30750. BABYLON.ArcRotateCamera = ArcRotateCamera;
  30751. })(BABYLON || (BABYLON = {}));
  30752. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  30753. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  30754. var BABYLON;
  30755. (function (BABYLON) {
  30756. var ArcRotateCameraInputsManager = (function (_super) {
  30757. __extends(ArcRotateCameraInputsManager, _super);
  30758. function ArcRotateCameraInputsManager(camera) {
  30759. return _super.call(this, camera) || this;
  30760. }
  30761. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  30762. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  30763. return this;
  30764. };
  30765. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  30766. this.add(new BABYLON.ArcRotateCameraPointersInput());
  30767. return this;
  30768. };
  30769. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  30770. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  30771. return this;
  30772. };
  30773. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  30774. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  30775. return this;
  30776. };
  30777. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  30778. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  30779. return this;
  30780. };
  30781. return ArcRotateCameraInputsManager;
  30782. }(BABYLON.CameraInputsManager));
  30783. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  30784. })(BABYLON || (BABYLON = {}));
  30785. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  30786. var BABYLON;
  30787. (function (BABYLON) {
  30788. var CubeTexture = (function (_super) {
  30789. __extends(CubeTexture, _super);
  30790. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format) {
  30791. if (onLoad === void 0) { onLoad = null; }
  30792. if (onError === void 0) { onError = null; }
  30793. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30794. var _this = _super.call(this, scene) || this;
  30795. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  30796. _this.name = rootUrl;
  30797. _this.url = rootUrl;
  30798. _this._noMipmap = noMipmap;
  30799. _this.hasAlpha = false;
  30800. _this._format = format;
  30801. if (!rootUrl && !files) {
  30802. return _this;
  30803. }
  30804. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  30805. if (!files) {
  30806. if (!extensions) {
  30807. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  30808. }
  30809. files = [];
  30810. for (var index = 0; index < extensions.length; index++) {
  30811. files.push(rootUrl + extensions[index]);
  30812. }
  30813. _this._extensions = extensions;
  30814. }
  30815. _this._files = files;
  30816. if (!_this._texture) {
  30817. if (!scene.useDelayedTextureLoading) {
  30818. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format);
  30819. }
  30820. else {
  30821. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30822. }
  30823. }
  30824. else if (onLoad) {
  30825. if (_this._texture.isReady) {
  30826. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  30827. }
  30828. else {
  30829. _this._texture.onLoadedCallbacks.push(onLoad);
  30830. }
  30831. }
  30832. _this.isCube = true;
  30833. _this._textureMatrix = BABYLON.Matrix.Identity();
  30834. return _this;
  30835. }
  30836. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  30837. return new CubeTexture("", scene, null, noMipmap, files);
  30838. };
  30839. // Methods
  30840. CubeTexture.prototype.delayLoad = function () {
  30841. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30842. return;
  30843. }
  30844. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30845. this._texture = this._getFromCache(this.url, this._noMipmap);
  30846. if (!this._texture) {
  30847. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  30848. }
  30849. };
  30850. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  30851. return this._textureMatrix;
  30852. };
  30853. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  30854. var texture = BABYLON.SerializationHelper.Parse(function () {
  30855. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  30856. }, parsedTexture, scene);
  30857. // Animations
  30858. if (parsedTexture.animations) {
  30859. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30860. var parsedAnimation = parsedTexture.animations[animationIndex];
  30861. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30862. }
  30863. }
  30864. return texture;
  30865. };
  30866. CubeTexture.prototype.clone = function () {
  30867. var _this = this;
  30868. return BABYLON.SerializationHelper.Clone(function () {
  30869. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  30870. }, this);
  30871. };
  30872. return CubeTexture;
  30873. }(BABYLON.BaseTexture));
  30874. BABYLON.CubeTexture = CubeTexture;
  30875. })(BABYLON || (BABYLON = {}));
  30876. //# sourceMappingURL=babylon.cubeTexture.js.map
  30877. var BABYLON;
  30878. (function (BABYLON) {
  30879. var RenderTargetTexture = (function (_super) {
  30880. __extends(RenderTargetTexture, _super);
  30881. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  30882. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  30883. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  30884. if (isCube === void 0) { isCube = false; }
  30885. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30886. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  30887. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  30888. if (isMulti === void 0) { isMulti = false; }
  30889. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  30890. _this.isCube = isCube;
  30891. /**
  30892. * Use this list to define the list of mesh you want to render.
  30893. */
  30894. _this.renderList = new Array();
  30895. _this.renderParticles = true;
  30896. _this.renderSprites = false;
  30897. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  30898. // Events
  30899. /**
  30900. * An event triggered when the texture is unbind.
  30901. * @type {BABYLON.Observable}
  30902. */
  30903. _this.onAfterUnbindObservable = new BABYLON.Observable();
  30904. /**
  30905. * An event triggered before rendering the texture
  30906. * @type {BABYLON.Observable}
  30907. */
  30908. _this.onBeforeRenderObservable = new BABYLON.Observable();
  30909. /**
  30910. * An event triggered after rendering the texture
  30911. * @type {BABYLON.Observable}
  30912. */
  30913. _this.onAfterRenderObservable = new BABYLON.Observable();
  30914. /**
  30915. * An event triggered after the texture clear
  30916. * @type {BABYLON.Observable}
  30917. */
  30918. _this.onClearObservable = new BABYLON.Observable();
  30919. _this._currentRefreshId = -1;
  30920. _this._refreshRate = 1;
  30921. _this._samples = 1;
  30922. _this.name = name;
  30923. _this.isRenderTarget = true;
  30924. _this._size = size;
  30925. _this._generateMipMaps = generateMipMaps;
  30926. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  30927. // Rendering groups
  30928. _this._renderingManager = new BABYLON.RenderingManager(scene);
  30929. if (isMulti) {
  30930. return _this;
  30931. }
  30932. _this._renderTargetOptions = {
  30933. generateMipMaps: generateMipMaps,
  30934. type: type,
  30935. samplingMode: samplingMode,
  30936. generateDepthBuffer: generateDepthBuffer,
  30937. generateStencilBuffer: generateStencilBuffer
  30938. };
  30939. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  30940. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30941. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30942. }
  30943. if (isCube) {
  30944. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  30945. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  30946. _this._textureMatrix = BABYLON.Matrix.Identity();
  30947. }
  30948. else {
  30949. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  30950. }
  30951. return _this;
  30952. }
  30953. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  30954. get: function () {
  30955. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  30956. },
  30957. enumerable: true,
  30958. configurable: true
  30959. });
  30960. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  30961. get: function () {
  30962. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  30963. },
  30964. enumerable: true,
  30965. configurable: true
  30966. });
  30967. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  30968. get: function () {
  30969. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  30970. },
  30971. enumerable: true,
  30972. configurable: true
  30973. });
  30974. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  30975. set: function (callback) {
  30976. if (this._onAfterUnbindObserver) {
  30977. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  30978. }
  30979. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  30980. },
  30981. enumerable: true,
  30982. configurable: true
  30983. });
  30984. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  30985. set: function (callback) {
  30986. if (this._onBeforeRenderObserver) {
  30987. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  30988. }
  30989. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  30990. },
  30991. enumerable: true,
  30992. configurable: true
  30993. });
  30994. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  30995. set: function (callback) {
  30996. if (this._onAfterRenderObserver) {
  30997. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  30998. }
  30999. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  31000. },
  31001. enumerable: true,
  31002. configurable: true
  31003. });
  31004. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  31005. set: function (callback) {
  31006. if (this._onClearObserver) {
  31007. this.onClearObservable.remove(this._onClearObserver);
  31008. }
  31009. this._onClearObserver = this.onClearObservable.add(callback);
  31010. },
  31011. enumerable: true,
  31012. configurable: true
  31013. });
  31014. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  31015. get: function () {
  31016. return this._renderTargetOptions;
  31017. },
  31018. enumerable: true,
  31019. configurable: true
  31020. });
  31021. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  31022. get: function () {
  31023. return this._samples;
  31024. },
  31025. set: function (value) {
  31026. if (this._samples === value) {
  31027. return;
  31028. }
  31029. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  31030. },
  31031. enumerable: true,
  31032. configurable: true
  31033. });
  31034. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  31035. this._currentRefreshId = -1;
  31036. };
  31037. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  31038. get: function () {
  31039. return this._refreshRate;
  31040. },
  31041. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  31042. set: function (value) {
  31043. this._refreshRate = value;
  31044. this.resetRefreshCounter();
  31045. },
  31046. enumerable: true,
  31047. configurable: true
  31048. });
  31049. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  31050. if (!this._postProcessManager) {
  31051. this._postProcessManager = new BABYLON.PostProcessManager(this.getScene());
  31052. this._postProcesses = new Array();
  31053. }
  31054. this._postProcesses.push(postProcess);
  31055. this._postProcesses[0].autoClear = false;
  31056. };
  31057. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  31058. if (!this._postProcesses) {
  31059. return;
  31060. }
  31061. if (dispose) {
  31062. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  31063. var postProcess = _a[_i];
  31064. postProcess.dispose();
  31065. postProcess = null;
  31066. }
  31067. }
  31068. this._postProcesses = [];
  31069. };
  31070. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  31071. if (!this._postProcesses) {
  31072. return;
  31073. }
  31074. var index = this._postProcesses.indexOf(postProcess);
  31075. if (index === -1) {
  31076. return;
  31077. }
  31078. this._postProcesses.splice(index, 1);
  31079. if (this._postProcesses.length > 0) {
  31080. this._postProcesses[0].autoClear = false;
  31081. }
  31082. };
  31083. RenderTargetTexture.prototype._shouldRender = function () {
  31084. if (this._currentRefreshId === -1) {
  31085. this._currentRefreshId = 1;
  31086. return true;
  31087. }
  31088. if (this.refreshRate === this._currentRefreshId) {
  31089. this._currentRefreshId = 1;
  31090. return true;
  31091. }
  31092. this._currentRefreshId++;
  31093. return false;
  31094. };
  31095. RenderTargetTexture.prototype.isReady = function () {
  31096. if (!this.getScene().renderTargetsEnabled) {
  31097. return false;
  31098. }
  31099. return _super.prototype.isReady.call(this);
  31100. };
  31101. RenderTargetTexture.prototype.getRenderSize = function () {
  31102. return this._size;
  31103. };
  31104. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  31105. get: function () {
  31106. return true;
  31107. },
  31108. enumerable: true,
  31109. configurable: true
  31110. });
  31111. RenderTargetTexture.prototype.scale = function (ratio) {
  31112. var newSize = this._size * ratio;
  31113. this.resize(newSize);
  31114. };
  31115. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  31116. if (this.isCube) {
  31117. return this._textureMatrix;
  31118. }
  31119. return _super.prototype.getReflectionTextureMatrix.call(this);
  31120. };
  31121. RenderTargetTexture.prototype.resize = function (size) {
  31122. this.releaseInternalTexture();
  31123. if (this.isCube) {
  31124. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  31125. }
  31126. else {
  31127. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  31128. }
  31129. };
  31130. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  31131. var scene = this.getScene();
  31132. var engine = scene.getEngine();
  31133. if (this.useCameraPostProcesses !== undefined) {
  31134. useCameraPostProcess = this.useCameraPostProcesses;
  31135. }
  31136. if (this._waitingRenderList) {
  31137. this.renderList = [];
  31138. for (var index = 0; index < this._waitingRenderList.length; index++) {
  31139. var id = this._waitingRenderList[index];
  31140. this.renderList.push(scene.getMeshByID(id));
  31141. }
  31142. delete this._waitingRenderList;
  31143. }
  31144. // Is predicate defined?
  31145. if (this.renderListPredicate) {
  31146. this.renderList.splice(0); // Clear previous renderList
  31147. var sceneMeshes = this.getScene().meshes;
  31148. for (var index = 0; index < sceneMeshes.length; index++) {
  31149. var mesh = sceneMeshes[index];
  31150. if (this.renderListPredicate(mesh)) {
  31151. this.renderList.push(mesh);
  31152. }
  31153. }
  31154. }
  31155. if (this.renderList && this.renderList.length === 0) {
  31156. return;
  31157. }
  31158. // Set custom projection.
  31159. // Needs to be before binding to prevent changing the aspect ratio.
  31160. var camera;
  31161. if (this.activeCamera) {
  31162. camera = this.activeCamera;
  31163. engine.setViewport(this.activeCamera.viewport);
  31164. if (this.activeCamera !== scene.activeCamera) {
  31165. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  31166. }
  31167. }
  31168. else {
  31169. camera = scene.activeCamera;
  31170. engine.setViewport(scene.activeCamera.viewport);
  31171. }
  31172. // Prepare renderingManager
  31173. this._renderingManager.reset();
  31174. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  31175. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  31176. var sceneRenderId = scene.getRenderId();
  31177. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  31178. var mesh = currentRenderList[meshIndex];
  31179. if (mesh) {
  31180. if (!mesh.isReady()) {
  31181. // Reset _currentRefreshId
  31182. this.resetRefreshCounter();
  31183. continue;
  31184. }
  31185. mesh._preActivateForIntermediateRendering(sceneRenderId);
  31186. var isMasked = void 0;
  31187. if (!this.renderList) {
  31188. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  31189. }
  31190. else {
  31191. isMasked = false;
  31192. }
  31193. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  31194. mesh._activate(sceneRenderId);
  31195. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31196. var subMesh = mesh.subMeshes[subIndex];
  31197. scene._activeIndices.addCount(subMesh.indexCount, false);
  31198. this._renderingManager.dispatch(subMesh);
  31199. }
  31200. }
  31201. }
  31202. }
  31203. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  31204. var particleSystem = scene.particleSystems[particleIndex];
  31205. if (!particleSystem.isStarted() || !particleSystem.emitter || !particleSystem.emitter.position || !particleSystem.emitter.isEnabled()) {
  31206. continue;
  31207. }
  31208. if (currentRenderList.indexOf(particleSystem.emitter) >= 0) {
  31209. this._renderingManager.dispatchParticles(particleSystem);
  31210. }
  31211. }
  31212. if (this.isCube) {
  31213. for (var face = 0; face < 6; face++) {
  31214. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  31215. scene.incrementRenderId();
  31216. scene.resetCachedMaterial();
  31217. }
  31218. }
  31219. else {
  31220. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  31221. }
  31222. this.onAfterUnbindObservable.notifyObservers(this);
  31223. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  31224. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  31225. }
  31226. engine.setViewport(scene.activeCamera.viewport);
  31227. scene.resetCachedMaterial();
  31228. };
  31229. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  31230. var _this = this;
  31231. var scene = this.getScene();
  31232. var engine = scene.getEngine();
  31233. // Bind
  31234. if (this._postProcessManager) {
  31235. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  31236. }
  31237. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  31238. if (this.isCube) {
  31239. engine.bindFramebuffer(this._texture, faceIndex);
  31240. }
  31241. else {
  31242. engine.bindFramebuffer(this._texture);
  31243. }
  31244. }
  31245. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  31246. // Clear
  31247. if (this.onClearObservable.hasObservers()) {
  31248. this.onClearObservable.notifyObservers(engine);
  31249. }
  31250. else {
  31251. engine.clear(scene.clearColor, true, true, true);
  31252. }
  31253. if (!this._doNotChangeAspectRatio) {
  31254. scene.updateTransformMatrix(true);
  31255. }
  31256. // Render
  31257. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  31258. if (this._postProcessManager) {
  31259. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses);
  31260. }
  31261. else if (useCameraPostProcess) {
  31262. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  31263. }
  31264. if (!this._doNotChangeAspectRatio) {
  31265. scene.updateTransformMatrix(true);
  31266. }
  31267. // Dump ?
  31268. if (dumpForDebug) {
  31269. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  31270. }
  31271. // Unbind
  31272. if (!this.isCube || faceIndex === 5) {
  31273. if (this.isCube) {
  31274. if (faceIndex === 5) {
  31275. engine.generateMipMapsForCubemap(this._texture);
  31276. }
  31277. }
  31278. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  31279. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  31280. });
  31281. }
  31282. else {
  31283. this.onAfterRenderObservable.notifyObservers(faceIndex);
  31284. }
  31285. };
  31286. /**
  31287. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  31288. * This allowed control for front to back rendering or reversly depending of the special needs.
  31289. *
  31290. * @param renderingGroupId The rendering group id corresponding to its index
  31291. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  31292. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  31293. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  31294. */
  31295. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  31296. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  31297. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  31298. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  31299. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  31300. };
  31301. /**
  31302. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  31303. *
  31304. * @param renderingGroupId The rendering group id corresponding to its index
  31305. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  31306. */
  31307. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  31308. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  31309. };
  31310. RenderTargetTexture.prototype.clone = function () {
  31311. var textureSize = this.getSize();
  31312. 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);
  31313. // Base texture
  31314. newTexture.hasAlpha = this.hasAlpha;
  31315. newTexture.level = this.level;
  31316. // RenderTarget Texture
  31317. newTexture.coordinatesMode = this.coordinatesMode;
  31318. newTexture.renderList = this.renderList.slice(0);
  31319. return newTexture;
  31320. };
  31321. RenderTargetTexture.prototype.serialize = function () {
  31322. if (!this.name) {
  31323. return null;
  31324. }
  31325. var serializationObject = _super.prototype.serialize.call(this);
  31326. serializationObject.renderTargetSize = this.getRenderSize();
  31327. serializationObject.renderList = [];
  31328. for (var index = 0; index < this.renderList.length; index++) {
  31329. serializationObject.renderList.push(this.renderList[index].id);
  31330. }
  31331. return serializationObject;
  31332. };
  31333. RenderTargetTexture.prototype.dispose = function () {
  31334. if (this._postProcessManager) {
  31335. this._postProcessManager.dispose();
  31336. this._postProcessManager = null;
  31337. }
  31338. this.clearPostProcesses(true);
  31339. _super.prototype.dispose.call(this);
  31340. };
  31341. return RenderTargetTexture;
  31342. }(BABYLON.Texture));
  31343. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  31344. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  31345. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  31346. BABYLON.RenderTargetTexture = RenderTargetTexture;
  31347. })(BABYLON || (BABYLON = {}));
  31348. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  31349. var BABYLON;
  31350. (function (BABYLON) {
  31351. ;
  31352. var MultiRenderTarget = (function (_super) {
  31353. __extends(MultiRenderTarget, _super);
  31354. function MultiRenderTarget(name, size, count, scene, options) {
  31355. var _this = this;
  31356. options = options || {};
  31357. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  31358. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  31359. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  31360. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  31361. if (!_this.isSupported) {
  31362. _this.dispose();
  31363. return;
  31364. }
  31365. var types = [];
  31366. var samplingModes = [];
  31367. for (var i = 0; i < count; i++) {
  31368. if (options.types && options.types[i]) {
  31369. types.push(options.types[i]);
  31370. }
  31371. else {
  31372. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  31373. }
  31374. if (options.samplingModes && options.samplingModes[i]) {
  31375. samplingModes.push(options.samplingModes[i]);
  31376. }
  31377. else {
  31378. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  31379. }
  31380. }
  31381. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  31382. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  31383. _this._count = count;
  31384. _this._size = size;
  31385. _this._multiRenderTargetOptions = {
  31386. samplingModes: samplingModes,
  31387. generateMipMaps: generateMipMaps,
  31388. generateDepthBuffer: generateDepthBuffer,
  31389. generateStencilBuffer: generateStencilBuffer,
  31390. generateDepthTexture: generateDepthTexture,
  31391. types: types,
  31392. textureCount: count
  31393. };
  31394. _this._webGLTextures = scene.getEngine().createMultipleRenderTarget(size, _this._multiRenderTargetOptions);
  31395. _this._createInternalTextures();
  31396. return _this;
  31397. }
  31398. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  31399. get: function () {
  31400. var engine = this.getScene().getEngine();
  31401. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  31402. },
  31403. enumerable: true,
  31404. configurable: true
  31405. });
  31406. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  31407. get: function () {
  31408. return this._textures;
  31409. },
  31410. enumerable: true,
  31411. configurable: true
  31412. });
  31413. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  31414. get: function () {
  31415. return this._textures[this._textures.length - 1];
  31416. },
  31417. enumerable: true,
  31418. configurable: true
  31419. });
  31420. MultiRenderTarget.prototype._createInternalTextures = function () {
  31421. this._textures = [];
  31422. for (var i = 0; i < this._webGLTextures.length; i++) {
  31423. var texture = new BABYLON.Texture(null, this.getScene());
  31424. texture._texture = this._webGLTextures[i];
  31425. this._textures.push(texture);
  31426. }
  31427. // Keeps references to frame buffer and stencil/depth buffer
  31428. this._texture = this._webGLTextures[0];
  31429. };
  31430. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  31431. get: function () {
  31432. return this._samples;
  31433. },
  31434. set: function (value) {
  31435. if (this._samples === value) {
  31436. return;
  31437. }
  31438. for (var i = 0; i < this._webGLTextures.length; i++) {
  31439. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._webGLTextures[i], value);
  31440. }
  31441. },
  31442. enumerable: true,
  31443. configurable: true
  31444. });
  31445. MultiRenderTarget.prototype.resize = function (size) {
  31446. this.releaseInternalTextures();
  31447. this._webGLTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  31448. this._createInternalTextures();
  31449. };
  31450. MultiRenderTarget.prototype.dispose = function () {
  31451. this.releaseInternalTextures();
  31452. _super.prototype.dispose.call(this);
  31453. };
  31454. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  31455. if (!this._webGLTextures) {
  31456. return;
  31457. }
  31458. for (var i = this._webGLTextures.length - 1; i >= 0; i--) {
  31459. if (this._webGLTextures[i] !== undefined) {
  31460. this.getScene().getEngine().releaseInternalTexture(this._webGLTextures[i]);
  31461. this._webGLTextures.splice(i, 1);
  31462. }
  31463. }
  31464. };
  31465. return MultiRenderTarget;
  31466. }(BABYLON.RenderTargetTexture));
  31467. BABYLON.MultiRenderTarget = MultiRenderTarget;
  31468. })(BABYLON || (BABYLON = {}));
  31469. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  31470. /// <reference path="babylon.renderTargetTexture.ts" />
  31471. var BABYLON;
  31472. (function (BABYLON) {
  31473. var MirrorTexture = (function (_super) {
  31474. __extends(MirrorTexture, _super);
  31475. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  31476. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  31477. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  31478. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  31479. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  31480. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  31481. _this._transformMatrix = BABYLON.Matrix.Zero();
  31482. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  31483. _this._blurKernelX = 0;
  31484. _this._blurKernelY = 0;
  31485. _this._blurRatio = 1.0;
  31486. _this.onBeforeRenderObservable.add(function () {
  31487. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  31488. _this._savedViewMatrix = scene.getViewMatrix();
  31489. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  31490. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  31491. scene.clipPlane = _this.mirrorPlane;
  31492. scene.getEngine().cullBackFaces = false;
  31493. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  31494. });
  31495. _this.onAfterRenderObservable.add(function () {
  31496. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  31497. scene.getEngine().cullBackFaces = true;
  31498. scene._mirroredCameraPosition = null;
  31499. delete scene.clipPlane;
  31500. });
  31501. return _this;
  31502. }
  31503. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  31504. get: function () {
  31505. return this._blurRatio;
  31506. },
  31507. set: function (value) {
  31508. if (this._blurRatio === value) {
  31509. return;
  31510. }
  31511. this._blurRatio = value;
  31512. this._preparePostProcesses();
  31513. },
  31514. enumerable: true,
  31515. configurable: true
  31516. });
  31517. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  31518. set: function (value) {
  31519. this.blurKernelX = value;
  31520. this.blurKernelY = value;
  31521. },
  31522. enumerable: true,
  31523. configurable: true
  31524. });
  31525. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  31526. get: function () {
  31527. return this._blurKernelX;
  31528. },
  31529. set: function (value) {
  31530. if (this._blurKernelX === value) {
  31531. return;
  31532. }
  31533. this._blurKernelX = value;
  31534. this._preparePostProcesses();
  31535. },
  31536. enumerable: true,
  31537. configurable: true
  31538. });
  31539. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  31540. get: function () {
  31541. return this._blurKernelY;
  31542. },
  31543. set: function (value) {
  31544. if (this._blurKernelY === value) {
  31545. return;
  31546. }
  31547. this._blurKernelY = value;
  31548. this._preparePostProcesses();
  31549. },
  31550. enumerable: true,
  31551. configurable: true
  31552. });
  31553. MirrorTexture.prototype._preparePostProcesses = function () {
  31554. this.clearPostProcesses(true);
  31555. if (this._blurKernelX && this._blurKernelY) {
  31556. var engine = this.getScene().getEngine();
  31557. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  31558. 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);
  31559. this._blurX.autoClear = false;
  31560. if (this._blurRatio === 1) {
  31561. this._blurX.outputTexture = this._texture;
  31562. }
  31563. else {
  31564. this._blurX.alwaysForcePOT = true;
  31565. }
  31566. 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);
  31567. this._blurY.autoClear = false;
  31568. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  31569. this.addPostProcess(this._blurX);
  31570. this.addPostProcess(this._blurY);
  31571. }
  31572. };
  31573. MirrorTexture.prototype.clone = function () {
  31574. var textureSize = this.getSize();
  31575. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  31576. // Base texture
  31577. newTexture.hasAlpha = this.hasAlpha;
  31578. newTexture.level = this.level;
  31579. // Mirror Texture
  31580. newTexture.mirrorPlane = this.mirrorPlane.clone();
  31581. newTexture.renderList = this.renderList.slice(0);
  31582. return newTexture;
  31583. };
  31584. MirrorTexture.prototype.serialize = function () {
  31585. if (!this.name) {
  31586. return null;
  31587. }
  31588. var serializationObject = _super.prototype.serialize.call(this);
  31589. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  31590. return serializationObject;
  31591. };
  31592. return MirrorTexture;
  31593. }(BABYLON.RenderTargetTexture));
  31594. BABYLON.MirrorTexture = MirrorTexture;
  31595. })(BABYLON || (BABYLON = {}));
  31596. //# sourceMappingURL=babylon.mirrorTexture.js.map
  31597. /// <reference path="babylon.renderTargetTexture.ts" />
  31598. var BABYLON;
  31599. (function (BABYLON) {
  31600. /**
  31601. * Creates a refraction texture used by refraction channel of the standard material.
  31602. * @param name the texture name
  31603. * @param size size of the underlying texture
  31604. * @param scene root scene
  31605. */
  31606. var RefractionTexture = (function (_super) {
  31607. __extends(RefractionTexture, _super);
  31608. function RefractionTexture(name, size, scene, generateMipMaps) {
  31609. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  31610. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  31611. _this.depth = 2.0;
  31612. _this.onBeforeRenderObservable.add(function () {
  31613. scene.clipPlane = _this.refractionPlane;
  31614. });
  31615. _this.onAfterRenderObservable.add(function () {
  31616. delete scene.clipPlane;
  31617. });
  31618. return _this;
  31619. }
  31620. RefractionTexture.prototype.clone = function () {
  31621. var textureSize = this.getSize();
  31622. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  31623. // Base texture
  31624. newTexture.hasAlpha = this.hasAlpha;
  31625. newTexture.level = this.level;
  31626. // Refraction Texture
  31627. newTexture.refractionPlane = this.refractionPlane.clone();
  31628. newTexture.renderList = this.renderList.slice(0);
  31629. newTexture.depth = this.depth;
  31630. return newTexture;
  31631. };
  31632. RefractionTexture.prototype.serialize = function () {
  31633. if (!this.name) {
  31634. return null;
  31635. }
  31636. var serializationObject = _super.prototype.serialize.call(this);
  31637. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  31638. serializationObject.depth = this.depth;
  31639. return serializationObject;
  31640. };
  31641. return RefractionTexture;
  31642. }(BABYLON.RenderTargetTexture));
  31643. BABYLON.RefractionTexture = RefractionTexture;
  31644. })(BABYLON || (BABYLON = {}));
  31645. //# sourceMappingURL=babylon.refractionTexture.js.map
  31646. /// <reference path="babylon.texture.ts" />
  31647. var BABYLON;
  31648. (function (BABYLON) {
  31649. var DynamicTexture = (function (_super) {
  31650. __extends(DynamicTexture, _super);
  31651. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  31652. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31653. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31654. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  31655. _this.name = name;
  31656. var engine = _this.getScene().getEngine();
  31657. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31658. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31659. _this._generateMipMaps = generateMipMaps;
  31660. if (options.getContext) {
  31661. _this._canvas = options;
  31662. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  31663. }
  31664. else {
  31665. _this._canvas = document.createElement("canvas");
  31666. if (options.width) {
  31667. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  31668. }
  31669. else {
  31670. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  31671. }
  31672. }
  31673. var textureSize = _this.getSize();
  31674. _this._canvas.width = textureSize.width;
  31675. _this._canvas.height = textureSize.height;
  31676. _this._context = _this._canvas.getContext("2d");
  31677. return _this;
  31678. }
  31679. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  31680. get: function () {
  31681. return true;
  31682. },
  31683. enumerable: true,
  31684. configurable: true
  31685. });
  31686. DynamicTexture.prototype._recreate = function (textureSize) {
  31687. this._canvas.width = textureSize.width;
  31688. this._canvas.height = textureSize.height;
  31689. this.releaseInternalTexture();
  31690. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  31691. };
  31692. DynamicTexture.prototype.scale = function (ratio) {
  31693. var textureSize = this.getSize();
  31694. textureSize.width *= ratio;
  31695. textureSize.height *= ratio;
  31696. this._recreate(textureSize);
  31697. };
  31698. DynamicTexture.prototype.scaleTo = function (width, height) {
  31699. var textureSize = this.getSize();
  31700. textureSize.width = width;
  31701. textureSize.height = height;
  31702. this._recreate(textureSize);
  31703. };
  31704. DynamicTexture.prototype.getContext = function () {
  31705. return this._context;
  31706. };
  31707. DynamicTexture.prototype.clear = function () {
  31708. var size = this.getSize();
  31709. this._context.fillRect(0, 0, size.width, size.height);
  31710. };
  31711. DynamicTexture.prototype.update = function (invertY) {
  31712. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  31713. };
  31714. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  31715. if (update === void 0) { update = true; }
  31716. var size = this.getSize();
  31717. if (clearColor) {
  31718. this._context.fillStyle = clearColor;
  31719. this._context.fillRect(0, 0, size.width, size.height);
  31720. }
  31721. this._context.font = font;
  31722. if (x === null || x === undefined) {
  31723. var textSize = this._context.measureText(text);
  31724. x = (size.width - textSize.width) / 2;
  31725. }
  31726. if (y === null || y === undefined) {
  31727. var fontSize = parseInt((font.replace(/\D/g, '')));
  31728. ;
  31729. y = (size.height / 2) + (fontSize / 3.65);
  31730. }
  31731. this._context.fillStyle = color;
  31732. this._context.fillText(text, x, y);
  31733. if (update) {
  31734. this.update(invertY);
  31735. }
  31736. };
  31737. DynamicTexture.prototype.clone = function () {
  31738. var textureSize = this.getSize();
  31739. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  31740. // Base texture
  31741. newTexture.hasAlpha = this.hasAlpha;
  31742. newTexture.level = this.level;
  31743. // Dynamic Texture
  31744. newTexture.wrapU = this.wrapU;
  31745. newTexture.wrapV = this.wrapV;
  31746. return newTexture;
  31747. };
  31748. return DynamicTexture;
  31749. }(BABYLON.Texture));
  31750. BABYLON.DynamicTexture = DynamicTexture;
  31751. })(BABYLON || (BABYLON = {}));
  31752. //# sourceMappingURL=babylon.dynamicTexture.js.map
  31753. var BABYLON;
  31754. (function (BABYLON) {
  31755. var VideoTexture = (function (_super) {
  31756. __extends(VideoTexture, _super);
  31757. /**
  31758. * Creates a video texture.
  31759. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  31760. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  31761. * @param {BABYLON.Scene} scene is obviously the current scene.
  31762. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  31763. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  31764. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  31765. */
  31766. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  31767. if (generateMipMaps === void 0) { generateMipMaps = false; }
  31768. if (invertY === void 0) { invertY = false; }
  31769. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31770. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  31771. _this._autoLaunch = true;
  31772. var urls;
  31773. _this.name = name;
  31774. if (urlsOrVideo instanceof HTMLVideoElement) {
  31775. _this.video = urlsOrVideo;
  31776. }
  31777. else {
  31778. urls = urlsOrVideo;
  31779. _this.video = document.createElement("video");
  31780. _this.video.autoplay = false;
  31781. _this.video.loop = true;
  31782. }
  31783. _this._generateMipMaps = generateMipMaps;
  31784. _this._samplingMode = samplingMode;
  31785. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  31786. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  31787. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  31788. }
  31789. else {
  31790. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31791. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31792. _this._generateMipMaps = false;
  31793. }
  31794. if (urls) {
  31795. _this.video.addEventListener("canplay", function () {
  31796. _this._createTexture();
  31797. });
  31798. urls.forEach(function (url) {
  31799. var source = document.createElement("source");
  31800. source.src = url;
  31801. _this.video.appendChild(source);
  31802. });
  31803. }
  31804. else {
  31805. _this._createTexture();
  31806. }
  31807. _this._lastUpdate = BABYLON.Tools.Now;
  31808. return _this;
  31809. }
  31810. VideoTexture.prototype.__setTextureReady = function () {
  31811. this._texture.isReady = true;
  31812. };
  31813. VideoTexture.prototype._createTexture = function () {
  31814. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  31815. if (this._autoLaunch) {
  31816. this._autoLaunch = false;
  31817. this.video.play();
  31818. }
  31819. this._setTextureReady = this.__setTextureReady.bind(this);
  31820. this.video.addEventListener("playing", this._setTextureReady);
  31821. };
  31822. VideoTexture.prototype.update = function () {
  31823. var now = BABYLON.Tools.Now;
  31824. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  31825. return false;
  31826. }
  31827. this._lastUpdate = now;
  31828. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  31829. return true;
  31830. };
  31831. VideoTexture.prototype.dispose = function () {
  31832. _super.prototype.dispose.call(this);
  31833. this.video.removeEventListener("playing", this._setTextureReady);
  31834. };
  31835. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  31836. var video = document.createElement("video");
  31837. var constraintsDeviceId;
  31838. if (constraints && constraints.deviceId) {
  31839. constraintsDeviceId = {
  31840. exact: constraints.deviceId
  31841. };
  31842. }
  31843. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  31844. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  31845. if (navigator.getUserMedia) {
  31846. navigator.getUserMedia({
  31847. video: {
  31848. deviceId: constraintsDeviceId,
  31849. width: {
  31850. min: (constraints && constraints.minWidth) || 256,
  31851. max: (constraints && constraints.maxWidth) || 640
  31852. },
  31853. height: {
  31854. min: (constraints && constraints.minHeight) || 256,
  31855. max: (constraints && constraints.maxHeight) || 480
  31856. }
  31857. }
  31858. }, function (stream) {
  31859. if (video.mozSrcObject !== undefined) {
  31860. video.mozSrcObject = stream;
  31861. }
  31862. else {
  31863. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  31864. }
  31865. video.play();
  31866. if (onReady) {
  31867. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  31868. }
  31869. }, function (e) {
  31870. BABYLON.Tools.Error(e.name);
  31871. });
  31872. }
  31873. };
  31874. return VideoTexture;
  31875. }(BABYLON.Texture));
  31876. BABYLON.VideoTexture = VideoTexture;
  31877. })(BABYLON || (BABYLON = {}));
  31878. //# sourceMappingURL=babylon.videoTexture.js.map
  31879. var BABYLON;
  31880. (function (BABYLON) {
  31881. var RawTexture = (function (_super) {
  31882. __extends(RawTexture, _super);
  31883. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  31884. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31885. if (invertY === void 0) { invertY = false; }
  31886. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31887. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  31888. _this.format = format;
  31889. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  31890. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31891. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31892. return _this;
  31893. }
  31894. RawTexture.prototype.update = function (data) {
  31895. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  31896. };
  31897. // Statics
  31898. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31899. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31900. if (invertY === void 0) { invertY = false; }
  31901. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31902. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  31903. };
  31904. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31905. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31906. if (invertY === void 0) { invertY = false; }
  31907. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31908. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31909. };
  31910. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31911. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31912. if (invertY === void 0) { invertY = false; }
  31913. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31914. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31915. };
  31916. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31917. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31918. if (invertY === void 0) { invertY = false; }
  31919. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31920. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  31921. };
  31922. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31923. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31924. if (invertY === void 0) { invertY = false; }
  31925. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31926. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  31927. };
  31928. return RawTexture;
  31929. }(BABYLON.Texture));
  31930. BABYLON.RawTexture = RawTexture;
  31931. })(BABYLON || (BABYLON = {}));
  31932. //# sourceMappingURL=babylon.rawTexture.js.map
  31933. var BABYLON;
  31934. (function (BABYLON) {
  31935. var Internals;
  31936. (function (Internals) {
  31937. /*
  31938. * Based on jsTGALoader - Javascript loader for TGA file
  31939. * By Vincent Thibault
  31940. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  31941. */
  31942. var TGATools = (function () {
  31943. function TGATools() {
  31944. }
  31945. TGATools.GetTGAHeader = function (data) {
  31946. var offset = 0;
  31947. var header = {
  31948. id_length: data[offset++],
  31949. colormap_type: data[offset++],
  31950. image_type: data[offset++],
  31951. colormap_index: data[offset++] | data[offset++] << 8,
  31952. colormap_length: data[offset++] | data[offset++] << 8,
  31953. colormap_size: data[offset++],
  31954. origin: [
  31955. data[offset++] | data[offset++] << 8,
  31956. data[offset++] | data[offset++] << 8
  31957. ],
  31958. width: data[offset++] | data[offset++] << 8,
  31959. height: data[offset++] | data[offset++] << 8,
  31960. pixel_size: data[offset++],
  31961. flags: data[offset++]
  31962. };
  31963. return header;
  31964. };
  31965. TGATools.UploadContent = function (gl, data) {
  31966. // Not enough data to contain header ?
  31967. if (data.length < 19) {
  31968. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  31969. return;
  31970. }
  31971. // Read Header
  31972. var offset = 18;
  31973. var header = TGATools.GetTGAHeader(data);
  31974. // Assume it's a valid Targa file.
  31975. if (header.id_length + offset > data.length) {
  31976. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  31977. return;
  31978. }
  31979. // Skip not needed data
  31980. offset += header.id_length;
  31981. var use_rle = false;
  31982. var use_pal = false;
  31983. var use_rgb = false;
  31984. var use_grey = false;
  31985. // Get some informations.
  31986. switch (header.image_type) {
  31987. case TGATools._TYPE_RLE_INDEXED:
  31988. use_rle = true;
  31989. case TGATools._TYPE_INDEXED:
  31990. use_pal = true;
  31991. break;
  31992. case TGATools._TYPE_RLE_RGB:
  31993. use_rle = true;
  31994. case TGATools._TYPE_RGB:
  31995. use_rgb = true;
  31996. break;
  31997. case TGATools._TYPE_RLE_GREY:
  31998. use_rle = true;
  31999. case TGATools._TYPE_GREY:
  32000. use_grey = true;
  32001. break;
  32002. }
  32003. var pixel_data;
  32004. var numAlphaBits = header.flags & 0xf;
  32005. var pixel_size = header.pixel_size >> 3;
  32006. var pixel_total = header.width * header.height * pixel_size;
  32007. // Read palettes
  32008. var palettes;
  32009. if (use_pal) {
  32010. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  32011. }
  32012. // Read LRE
  32013. if (use_rle) {
  32014. pixel_data = new Uint8Array(pixel_total);
  32015. var c, count, i;
  32016. var localOffset = 0;
  32017. var pixels = new Uint8Array(pixel_size);
  32018. while (offset < pixel_total && localOffset < pixel_total) {
  32019. c = data[offset++];
  32020. count = (c & 0x7f) + 1;
  32021. // RLE pixels
  32022. if (c & 0x80) {
  32023. // Bind pixel tmp array
  32024. for (i = 0; i < pixel_size; ++i) {
  32025. pixels[i] = data[offset++];
  32026. }
  32027. // Copy pixel array
  32028. for (i = 0; i < count; ++i) {
  32029. pixel_data.set(pixels, localOffset + i * pixel_size);
  32030. }
  32031. localOffset += pixel_size * count;
  32032. }
  32033. else {
  32034. count *= pixel_size;
  32035. for (i = 0; i < count; ++i) {
  32036. pixel_data[localOffset + i] = data[offset++];
  32037. }
  32038. localOffset += count;
  32039. }
  32040. }
  32041. }
  32042. else {
  32043. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  32044. }
  32045. // Load to texture
  32046. var x_start, y_start, x_step, y_step, y_end, x_end;
  32047. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  32048. default:
  32049. case TGATools._ORIGIN_UL:
  32050. x_start = 0;
  32051. x_step = 1;
  32052. x_end = header.width;
  32053. y_start = 0;
  32054. y_step = 1;
  32055. y_end = header.height;
  32056. break;
  32057. case TGATools._ORIGIN_BL:
  32058. x_start = 0;
  32059. x_step = 1;
  32060. x_end = header.width;
  32061. y_start = header.height - 1;
  32062. y_step = -1;
  32063. y_end = -1;
  32064. break;
  32065. case TGATools._ORIGIN_UR:
  32066. x_start = header.width - 1;
  32067. x_step = -1;
  32068. x_end = -1;
  32069. y_start = 0;
  32070. y_step = 1;
  32071. y_end = header.height;
  32072. break;
  32073. case TGATools._ORIGIN_BR:
  32074. x_start = header.width - 1;
  32075. x_step = -1;
  32076. x_end = -1;
  32077. y_start = header.height - 1;
  32078. y_step = -1;
  32079. y_end = -1;
  32080. break;
  32081. }
  32082. // Load the specify method
  32083. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  32084. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  32085. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  32086. };
  32087. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  32088. var image = pixel_data, colormap = palettes;
  32089. var width = header.width, height = header.height;
  32090. var color, i = 0, x, y;
  32091. var imageData = new Uint8Array(width * height * 4);
  32092. for (y = y_start; y !== y_end; y += y_step) {
  32093. for (x = x_start; x !== x_end; x += x_step, i++) {
  32094. color = image[i];
  32095. imageData[(x + width * y) * 4 + 3] = 255;
  32096. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  32097. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  32098. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  32099. }
  32100. }
  32101. return imageData;
  32102. };
  32103. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  32104. var image = pixel_data;
  32105. var width = header.width, height = header.height;
  32106. var color, i = 0, x, y;
  32107. var imageData = new Uint8Array(width * height * 4);
  32108. for (y = y_start; y !== y_end; y += y_step) {
  32109. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  32110. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  32111. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  32112. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  32113. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  32114. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  32115. }
  32116. }
  32117. return imageData;
  32118. };
  32119. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  32120. var image = pixel_data;
  32121. var width = header.width, height = header.height;
  32122. var i = 0, x, y;
  32123. var imageData = new Uint8Array(width * height * 4);
  32124. for (y = y_start; y !== y_end; y += y_step) {
  32125. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  32126. imageData[(x + width * y) * 4 + 3] = 255;
  32127. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  32128. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  32129. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  32130. }
  32131. }
  32132. return imageData;
  32133. };
  32134. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  32135. var image = pixel_data;
  32136. var width = header.width, height = header.height;
  32137. var i = 0, x, y;
  32138. var imageData = new Uint8Array(width * height * 4);
  32139. for (y = y_start; y !== y_end; y += y_step) {
  32140. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  32141. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  32142. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  32143. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  32144. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  32145. }
  32146. }
  32147. return imageData;
  32148. };
  32149. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  32150. var image = pixel_data;
  32151. var width = header.width, height = header.height;
  32152. var color, i = 0, x, y;
  32153. var imageData = new Uint8Array(width * height * 4);
  32154. for (y = y_start; y !== y_end; y += y_step) {
  32155. for (x = x_start; x !== x_end; x += x_step, i++) {
  32156. color = image[i];
  32157. imageData[(x + width * y) * 4 + 0] = color;
  32158. imageData[(x + width * y) * 4 + 1] = color;
  32159. imageData[(x + width * y) * 4 + 2] = color;
  32160. imageData[(x + width * y) * 4 + 3] = 255;
  32161. }
  32162. }
  32163. return imageData;
  32164. };
  32165. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  32166. var image = pixel_data;
  32167. var width = header.width, height = header.height;
  32168. var i = 0, x, y;
  32169. var imageData = new Uint8Array(width * height * 4);
  32170. for (y = y_start; y !== y_end; y += y_step) {
  32171. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  32172. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  32173. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  32174. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  32175. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  32176. }
  32177. }
  32178. return imageData;
  32179. };
  32180. return TGATools;
  32181. }());
  32182. TGATools._TYPE_NO_DATA = 0;
  32183. TGATools._TYPE_INDEXED = 1;
  32184. TGATools._TYPE_RGB = 2;
  32185. TGATools._TYPE_GREY = 3;
  32186. TGATools._TYPE_RLE_INDEXED = 9;
  32187. TGATools._TYPE_RLE_RGB = 10;
  32188. TGATools._TYPE_RLE_GREY = 11;
  32189. TGATools._ORIGIN_MASK = 0x30;
  32190. TGATools._ORIGIN_SHIFT = 0x04;
  32191. TGATools._ORIGIN_BL = 0x00;
  32192. TGATools._ORIGIN_BR = 0x01;
  32193. TGATools._ORIGIN_UL = 0x02;
  32194. TGATools._ORIGIN_UR = 0x03;
  32195. Internals.TGATools = TGATools;
  32196. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32197. })(BABYLON || (BABYLON = {}));
  32198. //# sourceMappingURL=babylon.tga.js.map
  32199. var BABYLON;
  32200. (function (BABYLON) {
  32201. var Internals;
  32202. (function (Internals) {
  32203. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  32204. // All values and structures referenced from:
  32205. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  32206. var DDS_MAGIC = 0x20534444;
  32207. 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;
  32208. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  32209. 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;
  32210. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  32211. function FourCCToInt32(value) {
  32212. return value.charCodeAt(0) +
  32213. (value.charCodeAt(1) << 8) +
  32214. (value.charCodeAt(2) << 16) +
  32215. (value.charCodeAt(3) << 24);
  32216. }
  32217. function Int32ToFourCC(value) {
  32218. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  32219. }
  32220. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  32221. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  32222. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  32223. var headerLengthInt = 31; // The header length in 32 bit ints
  32224. // Offsets into the header array
  32225. var off_magic = 0;
  32226. var off_size = 1;
  32227. var off_flags = 2;
  32228. var off_height = 3;
  32229. var off_width = 4;
  32230. var off_mipmapCount = 7;
  32231. var off_pfFlags = 20;
  32232. var off_pfFourCC = 21;
  32233. var off_RGBbpp = 22;
  32234. var off_RMask = 23;
  32235. var off_GMask = 24;
  32236. var off_BMask = 25;
  32237. var off_AMask = 26;
  32238. var off_caps1 = 27;
  32239. var off_caps2 = 28;
  32240. ;
  32241. var DDSTools = (function () {
  32242. function DDSTools() {
  32243. }
  32244. DDSTools.GetDDSInfo = function (arrayBuffer) {
  32245. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  32246. var mipmapCount = 1;
  32247. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  32248. mipmapCount = Math.max(1, header[off_mipmapCount]);
  32249. }
  32250. return {
  32251. width: header[off_width],
  32252. height: header[off_height],
  32253. mipmapCount: mipmapCount,
  32254. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  32255. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  32256. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  32257. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  32258. };
  32259. };
  32260. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  32261. var byteArray = new Uint8Array(dataLength);
  32262. var srcData = new Uint8Array(arrayBuffer);
  32263. var index = 0;
  32264. for (var y = height - 1; y >= 0; y--) {
  32265. for (var x = 0; x < width; x++) {
  32266. var srcPos = dataOffset + (x + y * width) * 4;
  32267. byteArray[index + 2] = srcData[srcPos];
  32268. byteArray[index + 1] = srcData[srcPos + 1];
  32269. byteArray[index] = srcData[srcPos + 2];
  32270. byteArray[index + 3] = srcData[srcPos + 3];
  32271. index += 4;
  32272. }
  32273. }
  32274. return byteArray;
  32275. };
  32276. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  32277. var byteArray = new Uint8Array(dataLength);
  32278. var srcData = new Uint8Array(arrayBuffer);
  32279. var index = 0;
  32280. for (var y = height - 1; y >= 0; y--) {
  32281. for (var x = 0; x < width; x++) {
  32282. var srcPos = dataOffset + (x + y * width) * 3;
  32283. byteArray[index + 2] = srcData[srcPos];
  32284. byteArray[index + 1] = srcData[srcPos + 1];
  32285. byteArray[index] = srcData[srcPos + 2];
  32286. index += 3;
  32287. }
  32288. }
  32289. return byteArray;
  32290. };
  32291. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  32292. var byteArray = new Uint8Array(dataLength);
  32293. var srcData = new Uint8Array(arrayBuffer);
  32294. var index = 0;
  32295. for (var y = height - 1; y >= 0; y--) {
  32296. for (var x = 0; x < width; x++) {
  32297. var srcPos = dataOffset + (x + y * width);
  32298. byteArray[index] = srcData[srcPos];
  32299. index++;
  32300. }
  32301. }
  32302. return byteArray;
  32303. };
  32304. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  32305. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  32306. if (header[off_magic] != DDS_MAGIC) {
  32307. BABYLON.Tools.Error("Invalid magic number in DDS header");
  32308. return;
  32309. }
  32310. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  32311. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  32312. return;
  32313. }
  32314. if (info.isFourCC) {
  32315. fourCC = header[off_pfFourCC];
  32316. switch (fourCC) {
  32317. case FOURCC_DXT1:
  32318. blockBytes = 8;
  32319. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  32320. break;
  32321. case FOURCC_DXT3:
  32322. blockBytes = 16;
  32323. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  32324. break;
  32325. case FOURCC_DXT5:
  32326. blockBytes = 16;
  32327. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  32328. break;
  32329. default:
  32330. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  32331. return;
  32332. }
  32333. }
  32334. mipmapCount = 1;
  32335. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  32336. mipmapCount = Math.max(1, header[off_mipmapCount]);
  32337. }
  32338. var bpp = header[off_RGBbpp];
  32339. for (var face = 0; face < faces; face++) {
  32340. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  32341. width = header[off_width];
  32342. height = header[off_height];
  32343. dataOffset = header[off_size] + 4;
  32344. for (i = 0; i < mipmapCount; ++i) {
  32345. if (info.isRGB) {
  32346. if (bpp === 24) {
  32347. dataLength = width * height * 3;
  32348. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  32349. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  32350. }
  32351. else {
  32352. dataLength = width * height * 4;
  32353. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  32354. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  32355. }
  32356. }
  32357. else if (info.isLuminance) {
  32358. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  32359. var unpaddedRowSize = width;
  32360. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  32361. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  32362. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  32363. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  32364. }
  32365. else {
  32366. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  32367. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  32368. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  32369. }
  32370. dataOffset += dataLength;
  32371. width *= 0.5;
  32372. height *= 0.5;
  32373. width = Math.max(1.0, width);
  32374. height = Math.max(1.0, height);
  32375. }
  32376. }
  32377. };
  32378. return DDSTools;
  32379. }());
  32380. Internals.DDSTools = DDSTools;
  32381. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32382. })(BABYLON || (BABYLON = {}));
  32383. //# sourceMappingURL=babylon.dds.js.map
  32384. var BABYLON;
  32385. (function (BABYLON) {
  32386. var Internals;
  32387. (function (Internals) {
  32388. /**
  32389. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  32390. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  32391. */
  32392. var KhronosTextureContainer = (function () {
  32393. /**
  32394. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  32395. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  32396. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  32397. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  32398. */
  32399. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  32400. this.arrayBuffer = arrayBuffer;
  32401. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  32402. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  32403. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  32404. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  32405. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  32406. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  32407. BABYLON.Tools.Error("texture missing KTX identifier");
  32408. return;
  32409. }
  32410. // load the reset of the header in native 32 bit int
  32411. var header = new Int32Array(this.arrayBuffer, 12, 13);
  32412. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  32413. var oppositeEndianess = header[0] === 0x01020304;
  32414. // read all the header elements in order they exist in the file, without modification (sans endainness)
  32415. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  32416. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  32417. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  32418. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  32419. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  32420. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  32421. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  32422. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  32423. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  32424. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  32425. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  32426. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  32427. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  32428. if (this.glType !== 0) {
  32429. BABYLON.Tools.Error("only compressed formats currently supported");
  32430. return;
  32431. }
  32432. else {
  32433. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  32434. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  32435. }
  32436. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  32437. BABYLON.Tools.Error("only 2D textures currently supported");
  32438. return;
  32439. }
  32440. if (this.numberOfArrayElements !== 0) {
  32441. BABYLON.Tools.Error("texture arrays not currently supported");
  32442. return;
  32443. }
  32444. if (this.numberOfFaces !== facesExpected) {
  32445. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  32446. return;
  32447. }
  32448. // we now have a completely validated file, so could use existence of loadType as success
  32449. // would need to make this more elaborate & adjust checks above to support more than one load type
  32450. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  32451. }
  32452. // not as fast hardware based, but will probably never need to use
  32453. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  32454. return ((val & 0xFF) << 24)
  32455. | ((val & 0xFF00) << 8)
  32456. | ((val >> 8) & 0xFF00)
  32457. | ((val >> 24) & 0xFF);
  32458. };
  32459. /**
  32460. * It is assumed that the texture has already been created & is currently bound
  32461. */
  32462. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  32463. switch (this.loadType) {
  32464. case KhronosTextureContainer.COMPRESSED_2D:
  32465. this._upload2DCompressedLevels(gl, loadMipmaps);
  32466. break;
  32467. case KhronosTextureContainer.TEX_2D:
  32468. case KhronosTextureContainer.COMPRESSED_3D:
  32469. case KhronosTextureContainer.TEX_3D:
  32470. }
  32471. };
  32472. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  32473. // initialize width & height for level 1
  32474. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  32475. var width = this.pixelWidth;
  32476. var height = this.pixelHeight;
  32477. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  32478. for (var level = 0; level < mipmapCount; level++) {
  32479. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  32480. for (var face = 0; face < this.numberOfFaces; face++) {
  32481. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  32482. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  32483. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  32484. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  32485. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  32486. }
  32487. width = Math.max(1.0, width * 0.5);
  32488. height = Math.max(1.0, height * 0.5);
  32489. }
  32490. };
  32491. return KhronosTextureContainer;
  32492. }());
  32493. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  32494. // load types
  32495. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  32496. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  32497. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  32498. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  32499. Internals.KhronosTextureContainer = KhronosTextureContainer;
  32500. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32501. })(BABYLON || (BABYLON = {}));
  32502. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  32503. var BABYLON;
  32504. (function (BABYLON) {
  32505. var PostProcess = (function () {
  32506. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  32507. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  32508. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  32509. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  32510. if (blockCompilation === void 0) { blockCompilation = false; }
  32511. this.name = name;
  32512. this.width = -1;
  32513. this.height = -1;
  32514. this.autoClear = true;
  32515. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  32516. /*
  32517. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  32518. Can only be used on a single postprocess or on the last one of a chain.
  32519. */
  32520. this.enablePixelPerfectMode = false;
  32521. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  32522. this.alwaysForcePOT = false;
  32523. this.samples = 1;
  32524. this._reusable = false;
  32525. this._textures = new BABYLON.SmartArray(2);
  32526. this._currentRenderTextureInd = 0;
  32527. this._scaleRatio = new BABYLON.Vector2(1, 1);
  32528. this._texelSize = BABYLON.Vector2.Zero();
  32529. // Events
  32530. /**
  32531. * An event triggered when the postprocess is activated.
  32532. * @type {BABYLON.Observable}
  32533. */
  32534. this.onActivateObservable = new BABYLON.Observable();
  32535. /**
  32536. * An event triggered when the postprocess changes its size.
  32537. * @type {BABYLON.Observable}
  32538. */
  32539. this.onSizeChangedObservable = new BABYLON.Observable();
  32540. /**
  32541. * An event triggered when the postprocess applies its effect.
  32542. * @type {BABYLON.Observable}
  32543. */
  32544. this.onApplyObservable = new BABYLON.Observable();
  32545. /**
  32546. * An event triggered before rendering the postprocess
  32547. * @type {BABYLON.Observable}
  32548. */
  32549. this.onBeforeRenderObservable = new BABYLON.Observable();
  32550. /**
  32551. * An event triggered after rendering the postprocess
  32552. * @type {BABYLON.Observable}
  32553. */
  32554. this.onAfterRenderObservable = new BABYLON.Observable();
  32555. if (camera != null) {
  32556. this._camera = camera;
  32557. this._scene = camera.getScene();
  32558. camera.attachPostProcess(this);
  32559. this._engine = this._scene.getEngine();
  32560. }
  32561. else {
  32562. this._engine = engine;
  32563. }
  32564. this._options = options;
  32565. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  32566. this._reusable = reusable || false;
  32567. this._textureType = textureType;
  32568. this._samplers = samplers || [];
  32569. this._samplers.push("textureSampler");
  32570. this._fragmentUrl = fragmentUrl;
  32571. this._vertexUrl = vertexUrl;
  32572. this._parameters = parameters || [];
  32573. this._parameters.push("scale");
  32574. this._indexParameters = indexParameters;
  32575. if (!blockCompilation) {
  32576. this.updateEffect(defines);
  32577. }
  32578. }
  32579. Object.defineProperty(PostProcess.prototype, "onActivate", {
  32580. set: function (callback) {
  32581. if (this._onActivateObserver) {
  32582. this.onActivateObservable.remove(this._onActivateObserver);
  32583. }
  32584. this._onActivateObserver = this.onActivateObservable.add(callback);
  32585. },
  32586. enumerable: true,
  32587. configurable: true
  32588. });
  32589. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  32590. set: function (callback) {
  32591. if (this._onSizeChangedObserver) {
  32592. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  32593. }
  32594. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  32595. },
  32596. enumerable: true,
  32597. configurable: true
  32598. });
  32599. Object.defineProperty(PostProcess.prototype, "onApply", {
  32600. set: function (callback) {
  32601. if (this._onApplyObserver) {
  32602. this.onApplyObservable.remove(this._onApplyObserver);
  32603. }
  32604. this._onApplyObserver = this.onApplyObservable.add(callback);
  32605. },
  32606. enumerable: true,
  32607. configurable: true
  32608. });
  32609. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  32610. set: function (callback) {
  32611. if (this._onBeforeRenderObserver) {
  32612. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  32613. }
  32614. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  32615. },
  32616. enumerable: true,
  32617. configurable: true
  32618. });
  32619. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  32620. set: function (callback) {
  32621. if (this._onAfterRenderObserver) {
  32622. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  32623. }
  32624. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  32625. },
  32626. enumerable: true,
  32627. configurable: true
  32628. });
  32629. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  32630. get: function () {
  32631. return this._textures.data[this._currentRenderTextureInd];
  32632. },
  32633. set: function (value) {
  32634. this._forcedOutputTexture = value;
  32635. },
  32636. enumerable: true,
  32637. configurable: true
  32638. });
  32639. PostProcess.prototype.getCamera = function () {
  32640. return this._camera;
  32641. };
  32642. Object.defineProperty(PostProcess.prototype, "texelSize", {
  32643. get: function () {
  32644. if (this._shareOutputWithPostProcess) {
  32645. return this._shareOutputWithPostProcess.texelSize;
  32646. }
  32647. if (this._forcedOutputTexture) {
  32648. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture._width, 1.0 / this._forcedOutputTexture._height);
  32649. }
  32650. return this._texelSize;
  32651. },
  32652. enumerable: true,
  32653. configurable: true
  32654. });
  32655. PostProcess.prototype.getEngine = function () {
  32656. return this._engine;
  32657. };
  32658. PostProcess.prototype.shareOutputWith = function (postProcess) {
  32659. this._disposeTextures();
  32660. this._shareOutputWithPostProcess = postProcess;
  32661. return this;
  32662. };
  32663. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters) {
  32664. this._effect = this._engine.createEffect({ vertex: this._vertexUrl, fragment: this._fragmentUrl }, ["position"], uniforms || this._parameters, samplers || this._samplers, defines !== undefined ? defines : "", null, null, null, indexParameters || this._indexParameters);
  32665. };
  32666. PostProcess.prototype.isReusable = function () {
  32667. return this._reusable;
  32668. };
  32669. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  32670. PostProcess.prototype.markTextureDirty = function () {
  32671. this.width = -1;
  32672. };
  32673. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  32674. var _this = this;
  32675. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  32676. camera = camera || this._camera;
  32677. var scene = camera.getScene();
  32678. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  32679. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  32680. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  32681. var desiredWidth = this._options.width || requiredWidth;
  32682. var desiredHeight = this._options.height || requiredHeight;
  32683. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  32684. if (!this._options.width) {
  32685. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode);
  32686. }
  32687. if (!this._options.height) {
  32688. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode);
  32689. }
  32690. }
  32691. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  32692. if (this._textures.length > 0) {
  32693. for (var i = 0; i < this._textures.length; i++) {
  32694. this._engine._releaseTexture(this._textures.data[i]);
  32695. }
  32696. this._textures.reset();
  32697. }
  32698. this.width = desiredWidth;
  32699. this.height = desiredHeight;
  32700. var textureSize = { width: this.width, height: this.height };
  32701. var textureOptions = {
  32702. generateMipMaps: false,
  32703. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  32704. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  32705. samplingMode: this.renderTargetSamplingMode,
  32706. type: this._textureType
  32707. };
  32708. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  32709. if (this._reusable) {
  32710. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  32711. }
  32712. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  32713. this.onSizeChangedObservable.notifyObservers(this);
  32714. }
  32715. this._textures.forEach(function (texture) {
  32716. if (texture.samples !== _this.samples) {
  32717. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  32718. }
  32719. });
  32720. }
  32721. var target;
  32722. if (this._shareOutputWithPostProcess) {
  32723. target = this._shareOutputWithPostProcess.outputTexture;
  32724. }
  32725. else if (this._forcedOutputTexture) {
  32726. target = this._forcedOutputTexture;
  32727. this.width = this._forcedOutputTexture._width;
  32728. this.height = this._forcedOutputTexture._height;
  32729. }
  32730. else {
  32731. target = this.outputTexture;
  32732. }
  32733. if (this.enablePixelPerfectMode) {
  32734. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  32735. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight);
  32736. }
  32737. else {
  32738. this._scaleRatio.copyFromFloats(1, 1);
  32739. this._engine.bindFramebuffer(target);
  32740. }
  32741. this.onActivateObservable.notifyObservers(camera);
  32742. // Clear
  32743. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  32744. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  32745. }
  32746. if (this._reusable) {
  32747. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  32748. }
  32749. };
  32750. Object.defineProperty(PostProcess.prototype, "isSupported", {
  32751. get: function () {
  32752. return this._effect.isSupported;
  32753. },
  32754. enumerable: true,
  32755. configurable: true
  32756. });
  32757. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  32758. get: function () {
  32759. if (this._shareOutputWithPostProcess) {
  32760. return this._shareOutputWithPostProcess.aspectRatio;
  32761. }
  32762. if (this._forcedOutputTexture) {
  32763. var size = this._forcedOutputTexture._width / this._forcedOutputTexture._height;
  32764. }
  32765. return this.width / this.height;
  32766. },
  32767. enumerable: true,
  32768. configurable: true
  32769. });
  32770. PostProcess.prototype.apply = function () {
  32771. // Check
  32772. if (!this._effect || !this._effect.isReady())
  32773. return null;
  32774. // States
  32775. this._engine.enableEffect(this._effect);
  32776. this._engine.setState(false);
  32777. this._engine.setDepthBuffer(false);
  32778. this._engine.setDepthWrite(false);
  32779. // Alpha
  32780. this._engine.setAlphaMode(this.alphaMode);
  32781. if (this.alphaConstants) {
  32782. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  32783. }
  32784. // Texture
  32785. var source;
  32786. if (this._shareOutputWithPostProcess) {
  32787. source = this._shareOutputWithPostProcess.outputTexture;
  32788. }
  32789. else if (this._forcedOutputTexture) {
  32790. source = this._forcedOutputTexture;
  32791. }
  32792. else {
  32793. source = this.outputTexture;
  32794. }
  32795. this._effect._bindTexture("textureSampler", source);
  32796. // Parameters
  32797. this._effect.setVector2("scale", this._scaleRatio);
  32798. this.onApplyObservable.notifyObservers(this._effect);
  32799. return this._effect;
  32800. };
  32801. PostProcess.prototype._disposeTextures = function () {
  32802. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  32803. return;
  32804. }
  32805. if (this._textures.length > 0) {
  32806. for (var i = 0; i < this._textures.length; i++) {
  32807. this._engine._releaseTexture(this._textures.data[i]);
  32808. }
  32809. }
  32810. this._textures.dispose();
  32811. };
  32812. PostProcess.prototype.dispose = function (camera) {
  32813. camera = camera || this._camera;
  32814. this._disposeTextures();
  32815. if (!camera) {
  32816. return;
  32817. }
  32818. camera.detachPostProcess(this);
  32819. var index = camera._postProcesses.indexOf(this);
  32820. if (index === 0 && camera._postProcesses.length > 0) {
  32821. this._camera._postProcesses[0].markTextureDirty();
  32822. }
  32823. this.onActivateObservable.clear();
  32824. this.onAfterRenderObservable.clear();
  32825. this.onApplyObservable.clear();
  32826. this.onBeforeRenderObservable.clear();
  32827. this.onSizeChangedObservable.clear();
  32828. };
  32829. return PostProcess;
  32830. }());
  32831. BABYLON.PostProcess = PostProcess;
  32832. })(BABYLON || (BABYLON = {}));
  32833. //# sourceMappingURL=babylon.postProcess.js.map
  32834. var BABYLON;
  32835. (function (BABYLON) {
  32836. var PassPostProcess = (function (_super) {
  32837. __extends(PassPostProcess, _super);
  32838. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  32839. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  32840. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  32841. }
  32842. return PassPostProcess;
  32843. }(BABYLON.PostProcess));
  32844. BABYLON.PassPostProcess = PassPostProcess;
  32845. })(BABYLON || (BABYLON = {}));
  32846. //# sourceMappingURL=babylon.passPostProcess.js.map
  32847. var BABYLON;
  32848. (function (BABYLON) {
  32849. var ShadowGenerator = (function () {
  32850. /**
  32851. * Creates a ShadowGenerator object.
  32852. * A ShadowGenerator is the required tool to use the shadows.
  32853. * Each light casting shadows needs to use its own ShadowGenerator.
  32854. * Required parameters :
  32855. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  32856. * - `light`: the light object generating the shadows.
  32857. * - `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.
  32858. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  32859. */
  32860. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  32861. // Members
  32862. this._bias = 0.00005;
  32863. this._blurBoxOffset = 1;
  32864. this._blurScale = 2;
  32865. this._blurKernel = 1;
  32866. this._useKernelBlur = false;
  32867. this._filter = ShadowGenerator.FILTER_NONE;
  32868. this._darkness = 0;
  32869. this._transparencyShadow = false;
  32870. this.forceBackFacesOnly = false;
  32871. this._lightDirection = BABYLON.Vector3.Zero();
  32872. this._viewMatrix = BABYLON.Matrix.Zero();
  32873. this._projectionMatrix = BABYLON.Matrix.Zero();
  32874. this._transformMatrix = BABYLON.Matrix.Zero();
  32875. this._worldViewProjection = BABYLON.Matrix.Zero();
  32876. this._currentFaceIndex = 0;
  32877. this._currentFaceIndexCache = 0;
  32878. this._isCube = false;
  32879. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  32880. this._mapSize = mapSize;
  32881. this._light = light;
  32882. this._scene = light.getScene();
  32883. light._shadowGenerator = this;
  32884. // Texture type fallback from float to int if not supported.
  32885. var caps = this._scene.getEngine().getCaps();
  32886. if (!useFullFloatFirst) {
  32887. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  32888. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  32889. }
  32890. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  32891. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  32892. }
  32893. else {
  32894. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  32895. }
  32896. }
  32897. else {
  32898. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  32899. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  32900. }
  32901. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  32902. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  32903. }
  32904. else {
  32905. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  32906. }
  32907. }
  32908. this._initializeGenerator();
  32909. }
  32910. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  32911. // Static
  32912. get: function () {
  32913. return ShadowGenerator._FILTER_NONE;
  32914. },
  32915. enumerable: true,
  32916. configurable: true
  32917. });
  32918. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  32919. get: function () {
  32920. return ShadowGenerator._FILTER_POISSONSAMPLING;
  32921. },
  32922. enumerable: true,
  32923. configurable: true
  32924. });
  32925. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  32926. get: function () {
  32927. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  32928. },
  32929. enumerable: true,
  32930. configurable: true
  32931. });
  32932. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  32933. get: function () {
  32934. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  32935. },
  32936. enumerable: true,
  32937. configurable: true
  32938. });
  32939. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  32940. get: function () {
  32941. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  32942. },
  32943. enumerable: true,
  32944. configurable: true
  32945. });
  32946. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  32947. get: function () {
  32948. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  32949. },
  32950. enumerable: true,
  32951. configurable: true
  32952. });
  32953. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  32954. get: function () {
  32955. return this._bias;
  32956. },
  32957. set: function (bias) {
  32958. this._bias = bias;
  32959. },
  32960. enumerable: true,
  32961. configurable: true
  32962. });
  32963. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  32964. get: function () {
  32965. return this._blurBoxOffset;
  32966. },
  32967. set: function (value) {
  32968. if (this._blurBoxOffset === value) {
  32969. return;
  32970. }
  32971. this._blurBoxOffset = value;
  32972. this._disposeBlurPostProcesses();
  32973. },
  32974. enumerable: true,
  32975. configurable: true
  32976. });
  32977. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  32978. get: function () {
  32979. return this._blurScale;
  32980. },
  32981. set: function (value) {
  32982. if (this._blurScale === value) {
  32983. return;
  32984. }
  32985. this._blurScale = value;
  32986. this._disposeBlurPostProcesses();
  32987. },
  32988. enumerable: true,
  32989. configurable: true
  32990. });
  32991. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  32992. get: function () {
  32993. return this._blurKernel;
  32994. },
  32995. set: function (value) {
  32996. if (this._blurKernel === value) {
  32997. return;
  32998. }
  32999. this._blurKernel = value;
  33000. this._disposeBlurPostProcesses();
  33001. },
  33002. enumerable: true,
  33003. configurable: true
  33004. });
  33005. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  33006. get: function () {
  33007. return this._useKernelBlur;
  33008. },
  33009. set: function (value) {
  33010. if (this._useKernelBlur === value) {
  33011. return;
  33012. }
  33013. this._useKernelBlur = value;
  33014. this._disposeBlurPostProcesses();
  33015. },
  33016. enumerable: true,
  33017. configurable: true
  33018. });
  33019. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  33020. get: function () {
  33021. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  33022. },
  33023. set: function (value) {
  33024. this._depthScale = value;
  33025. },
  33026. enumerable: true,
  33027. configurable: true
  33028. });
  33029. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  33030. get: function () {
  33031. return this._filter;
  33032. },
  33033. set: function (value) {
  33034. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  33035. if (this._light.needCube()) {
  33036. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  33037. this.useExponentialShadowMap = true;
  33038. }
  33039. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  33040. this.useCloseExponentialShadowMap = true;
  33041. }
  33042. }
  33043. if (this._filter === value) {
  33044. return;
  33045. }
  33046. this._filter = value;
  33047. this._disposeBlurPostProcesses();
  33048. this._applyFilterValues();
  33049. this._light._markMeshesAsLightDirty();
  33050. },
  33051. enumerable: true,
  33052. configurable: true
  33053. });
  33054. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  33055. get: function () {
  33056. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  33057. },
  33058. set: function (value) {
  33059. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  33060. },
  33061. enumerable: true,
  33062. configurable: true
  33063. });
  33064. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  33065. get: function () {
  33066. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  33067. return this.useExponentialShadowMap;
  33068. },
  33069. set: function (value) {
  33070. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  33071. this.useExponentialShadowMap = value;
  33072. },
  33073. enumerable: true,
  33074. configurable: true
  33075. });
  33076. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  33077. get: function () {
  33078. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  33079. return this.useBlurExponentialShadowMap;
  33080. },
  33081. set: function (value) {
  33082. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  33083. this.useBlurExponentialShadowMap = value;
  33084. },
  33085. enumerable: true,
  33086. configurable: true
  33087. });
  33088. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  33089. get: function () {
  33090. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  33091. },
  33092. set: function (value) {
  33093. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  33094. },
  33095. enumerable: true,
  33096. configurable: true
  33097. });
  33098. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  33099. get: function () {
  33100. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  33101. },
  33102. set: function (value) {
  33103. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  33104. },
  33105. enumerable: true,
  33106. configurable: true
  33107. });
  33108. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  33109. get: function () {
  33110. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  33111. },
  33112. set: function (value) {
  33113. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  33114. },
  33115. enumerable: true,
  33116. configurable: true
  33117. });
  33118. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  33119. get: function () {
  33120. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  33121. },
  33122. set: function (value) {
  33123. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  33124. },
  33125. enumerable: true,
  33126. configurable: true
  33127. });
  33128. /**
  33129. * Returns the darkness value (float).
  33130. */
  33131. ShadowGenerator.prototype.getDarkness = function () {
  33132. return this._darkness;
  33133. };
  33134. /**
  33135. * Sets the ShadowGenerator darkness value (float <= 1.0).
  33136. * Returns the ShadowGenerator.
  33137. */
  33138. ShadowGenerator.prototype.setDarkness = function (darkness) {
  33139. if (darkness >= 1.0)
  33140. this._darkness = 1.0;
  33141. else if (darkness <= 0.0)
  33142. this._darkness = 0.0;
  33143. else
  33144. this._darkness = darkness;
  33145. return this;
  33146. };
  33147. /**
  33148. * Sets the ability to have transparent shadow (boolean).
  33149. * Returns the ShadowGenerator.
  33150. */
  33151. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  33152. this._transparencyShadow = hasShadow;
  33153. return this;
  33154. };
  33155. /**
  33156. * Returns a RenderTargetTexture object : the shadow map texture.
  33157. */
  33158. ShadowGenerator.prototype.getShadowMap = function () {
  33159. return this._shadowMap;
  33160. };
  33161. /**
  33162. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  33163. */
  33164. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  33165. if (this._shadowMap2) {
  33166. return this._shadowMap2;
  33167. }
  33168. return this._shadowMap;
  33169. };
  33170. /**
  33171. * Returns the associated light object.
  33172. */
  33173. ShadowGenerator.prototype.getLight = function () {
  33174. return this._light;
  33175. };
  33176. ShadowGenerator.prototype._initializeGenerator = function () {
  33177. this._light._markMeshesAsLightDirty();
  33178. this._initializeShadowMap();
  33179. };
  33180. ShadowGenerator.prototype._initializeShadowMap = function () {
  33181. var _this = this;
  33182. // Render target
  33183. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  33184. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33185. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33186. this._shadowMap.anisotropicFilteringLevel = 1;
  33187. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33188. this._shadowMap.renderParticles = false;
  33189. // Record Face Index before render.
  33190. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  33191. _this._currentFaceIndex = faceIndex;
  33192. });
  33193. // Custom render function.
  33194. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  33195. // Blur if required afer render.
  33196. this._shadowMap.onAfterUnbindObservable.add(function () {
  33197. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  33198. return;
  33199. }
  33200. if (!_this._blurPostProcesses) {
  33201. _this._initializeBlurRTTAndPostProcesses();
  33202. }
  33203. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, _this.getShadowMapForRendering().getInternalTexture());
  33204. });
  33205. // Clear according to the chosen filter.
  33206. this._shadowMap.onClearObservable.add(function (engine) {
  33207. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  33208. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  33209. }
  33210. else {
  33211. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  33212. }
  33213. });
  33214. };
  33215. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  33216. var _this = this;
  33217. var engine = this._scene.getEngine();
  33218. var targetSize = this._mapSize / this.blurScale;
  33219. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  33220. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  33221. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33222. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33223. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33224. }
  33225. if (this.useKernelBlur) {
  33226. 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);
  33227. this._kernelBlurXPostprocess.width = targetSize;
  33228. this._kernelBlurXPostprocess.height = targetSize;
  33229. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  33230. effect.setTexture("textureSampler", _this._shadowMap);
  33231. });
  33232. 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);
  33233. this._kernelBlurXPostprocess.autoClear = false;
  33234. this._kernelBlurYPostprocess.autoClear = false;
  33235. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  33236. }
  33237. else {
  33238. 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);
  33239. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  33240. effect.setFloat2("screenSize", targetSize, targetSize);
  33241. effect.setTexture("textureSampler", _this._shadowMap);
  33242. });
  33243. this._boxBlurPostprocess.autoClear = false;
  33244. this._blurPostProcesses = [this._boxBlurPostprocess];
  33245. }
  33246. };
  33247. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  33248. var index;
  33249. for (index = 0; index < opaqueSubMeshes.length; index++) {
  33250. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  33251. }
  33252. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  33253. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  33254. }
  33255. if (this._transparencyShadow) {
  33256. for (index = 0; index < transparentSubMeshes.length; index++) {
  33257. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  33258. }
  33259. }
  33260. };
  33261. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  33262. var _this = this;
  33263. var mesh = subMesh.getRenderingMesh();
  33264. var scene = this._scene;
  33265. var engine = scene.getEngine();
  33266. // Culling
  33267. engine.setState(subMesh.getMaterial().backFaceCulling);
  33268. // Managing instances
  33269. var batch = mesh._getInstancesRenderList(subMesh._id);
  33270. if (batch.mustReturn) {
  33271. return;
  33272. }
  33273. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  33274. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  33275. engine.enableEffect(this._effect);
  33276. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  33277. var material = subMesh.getMaterial();
  33278. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  33279. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  33280. this._effect.setVector3("lightPosition", this.getLight().position);
  33281. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  33282. // Alpha test
  33283. if (material && material.needAlphaTesting()) {
  33284. var alphaTexture = material.getAlphaTestTexture();
  33285. if (alphaTexture) {
  33286. this._effect.setTexture("diffuseSampler", alphaTexture);
  33287. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  33288. }
  33289. }
  33290. // Bones
  33291. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33292. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  33293. }
  33294. if (this.forceBackFacesOnly) {
  33295. engine.setState(true, 0, false, true);
  33296. }
  33297. // Draw
  33298. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  33299. if (this.forceBackFacesOnly) {
  33300. engine.setState(true, 0, false, false);
  33301. }
  33302. }
  33303. else {
  33304. // Need to reset refresh rate of the shadowMap
  33305. this._shadowMap.resetRefreshCounter();
  33306. }
  33307. };
  33308. ShadowGenerator.prototype._applyFilterValues = function () {
  33309. if (this.filter === ShadowGenerator.FILTER_NONE) {
  33310. this._shadowMap.anisotropicFilteringLevel = 1;
  33311. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  33312. }
  33313. else {
  33314. this._shadowMap.anisotropicFilteringLevel = 16;
  33315. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33316. }
  33317. };
  33318. /**
  33319. * Boolean : true when the ShadowGenerator is finally computed.
  33320. */
  33321. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  33322. var defines = [];
  33323. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  33324. defines.push("#define FLOAT");
  33325. }
  33326. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  33327. defines.push("#define ESM");
  33328. }
  33329. var attribs = [BABYLON.VertexBuffer.PositionKind];
  33330. var mesh = subMesh.getMesh();
  33331. var material = subMesh.getMaterial();
  33332. // Alpha test
  33333. if (material && material.needAlphaTesting()) {
  33334. defines.push("#define ALPHATEST");
  33335. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33336. attribs.push(BABYLON.VertexBuffer.UVKind);
  33337. defines.push("#define UV1");
  33338. }
  33339. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33340. var alphaTexture = material.getAlphaTestTexture();
  33341. if (alphaTexture.coordinatesIndex === 1) {
  33342. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  33343. defines.push("#define UV2");
  33344. }
  33345. }
  33346. }
  33347. // Bones
  33348. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  33349. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33350. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33351. if (mesh.numBoneInfluencers > 4) {
  33352. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33353. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33354. }
  33355. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  33356. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  33357. }
  33358. else {
  33359. defines.push("#define NUM_BONE_INFLUENCERS 0");
  33360. }
  33361. // Instances
  33362. if (useInstances) {
  33363. defines.push("#define INSTANCES");
  33364. attribs.push("world0");
  33365. attribs.push("world1");
  33366. attribs.push("world2");
  33367. attribs.push("world3");
  33368. }
  33369. // Get correct effect
  33370. var join = defines.join("\n");
  33371. if (this._cachedDefines !== join) {
  33372. this._cachedDefines = join;
  33373. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  33374. }
  33375. return this._effect.isReady();
  33376. };
  33377. /**
  33378. * This creates the defines related to the standard BJS materials.
  33379. */
  33380. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  33381. var scene = this._scene;
  33382. var light = this._light;
  33383. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  33384. return;
  33385. }
  33386. defines["SHADOW" + lightIndex] = true;
  33387. if (this.usePoissonSampling) {
  33388. defines["SHADOWPCF" + lightIndex] = true;
  33389. }
  33390. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  33391. defines["SHADOWESM" + lightIndex] = true;
  33392. }
  33393. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  33394. defines["SHADOWCLOSEESM" + lightIndex] = true;
  33395. }
  33396. if (light.needCube()) {
  33397. defines["SHADOWCUBE" + lightIndex] = true;
  33398. }
  33399. };
  33400. /**
  33401. * This binds shadow lights related to the standard BJS materials.
  33402. * It implies the unifroms available on the materials are the standard BJS ones.
  33403. */
  33404. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  33405. var light = this._light;
  33406. var scene = this._scene;
  33407. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  33408. return;
  33409. }
  33410. if (!light.needCube()) {
  33411. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  33412. }
  33413. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  33414. light._uniformBuffer.updateFloat3("shadowsInfo", this.getDarkness(), this.blurScale / this.getShadowMap().getSize().width, this.depthScale, lightIndex);
  33415. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera), lightIndex);
  33416. };
  33417. // Methods
  33418. /**
  33419. * Returns a Matrix object : the updated transformation matrix.
  33420. */
  33421. ShadowGenerator.prototype.getTransformMatrix = function () {
  33422. var scene = this._scene;
  33423. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  33424. return this._transformMatrix;
  33425. }
  33426. this._currentRenderID = scene.getRenderId();
  33427. this._currentFaceIndexCache = this._currentFaceIndex;
  33428. var lightPosition = this._light.position;
  33429. if (this._light.computeTransformedInformation()) {
  33430. lightPosition = this._light.transformedPosition;
  33431. }
  33432. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  33433. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  33434. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  33435. }
  33436. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  33437. this._cachedPosition = lightPosition.clone();
  33438. this._cachedDirection = this._lightDirection.clone();
  33439. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  33440. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  33441. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  33442. }
  33443. return this._transformMatrix;
  33444. };
  33445. ShadowGenerator.prototype.recreateShadowMap = function () {
  33446. // Track render list.
  33447. var renderList = this._shadowMap.renderList;
  33448. // Clean up existing data.
  33449. this._disposeRTTandPostProcesses();
  33450. // Reinitializes.
  33451. this._initializeGenerator();
  33452. // Reaffect the filter to ensure a correct fallback if necessary.
  33453. this.filter = this.filter;
  33454. // Reaffect the filter.
  33455. this._applyFilterValues();
  33456. // Reaffect Render List.
  33457. this._shadowMap.renderList = renderList;
  33458. };
  33459. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  33460. if (this._shadowMap2) {
  33461. this._shadowMap2.dispose();
  33462. this._shadowMap2 = null;
  33463. }
  33464. if (this._downSamplePostprocess) {
  33465. this._downSamplePostprocess.dispose();
  33466. this._downSamplePostprocess = null;
  33467. }
  33468. if (this._boxBlurPostprocess) {
  33469. this._boxBlurPostprocess.dispose();
  33470. this._boxBlurPostprocess = null;
  33471. }
  33472. if (this._kernelBlurXPostprocess) {
  33473. this._kernelBlurXPostprocess.dispose();
  33474. this._kernelBlurXPostprocess = null;
  33475. }
  33476. if (this._kernelBlurYPostprocess) {
  33477. this._kernelBlurYPostprocess.dispose();
  33478. this._kernelBlurYPostprocess = null;
  33479. }
  33480. this._blurPostProcesses = null;
  33481. };
  33482. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  33483. if (this._shadowMap) {
  33484. this._shadowMap.dispose();
  33485. this._shadowMap = null;
  33486. }
  33487. this._disposeBlurPostProcesses();
  33488. };
  33489. /**
  33490. * Disposes the ShadowGenerator.
  33491. * Returns nothing.
  33492. */
  33493. ShadowGenerator.prototype.dispose = function () {
  33494. this._disposeRTTandPostProcesses();
  33495. this._light._shadowGenerator = null;
  33496. this._light._markMeshesAsLightDirty();
  33497. };
  33498. /**
  33499. * Serializes the ShadowGenerator and returns a serializationObject.
  33500. */
  33501. ShadowGenerator.prototype.serialize = function () {
  33502. var serializationObject = {};
  33503. var shadowMap = this.getShadowMap();
  33504. serializationObject.lightId = this._light.id;
  33505. serializationObject.mapSize = shadowMap.getRenderSize();
  33506. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  33507. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  33508. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  33509. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  33510. serializationObject.usePoissonSampling = this.usePoissonSampling;
  33511. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  33512. serializationObject.depthScale = this.depthScale;
  33513. serializationObject.darkness = this.getDarkness();
  33514. serializationObject.blurBoxOffset = this.blurBoxOffset;
  33515. serializationObject.blurKernel = this.blurKernel;
  33516. serializationObject.blurScale = this.blurScale;
  33517. serializationObject.useKernelBlur = this.useKernelBlur;
  33518. serializationObject.transparencyShadow = this._transparencyShadow;
  33519. serializationObject.renderList = [];
  33520. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  33521. var mesh = shadowMap.renderList[meshIndex];
  33522. serializationObject.renderList.push(mesh.id);
  33523. }
  33524. return serializationObject;
  33525. };
  33526. /**
  33527. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  33528. */
  33529. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  33530. //casting to point light, as light is missing the position attr and typescript complains.
  33531. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  33532. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  33533. var shadowMap = shadowGenerator.getShadowMap();
  33534. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  33535. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  33536. meshes.forEach(function (mesh) {
  33537. shadowMap.renderList.push(mesh);
  33538. });
  33539. }
  33540. if (parsedShadowGenerator.usePoissonSampling) {
  33541. shadowGenerator.usePoissonSampling = true;
  33542. }
  33543. else if (parsedShadowGenerator.useExponentialShadowMap) {
  33544. shadowGenerator.useExponentialShadowMap = true;
  33545. }
  33546. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  33547. shadowGenerator.useBlurExponentialShadowMap = true;
  33548. }
  33549. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  33550. shadowGenerator.useCloseExponentialShadowMap = true;
  33551. }
  33552. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  33553. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  33554. }
  33555. else if (parsedShadowGenerator.useVarianceShadowMap) {
  33556. shadowGenerator.useExponentialShadowMap = true;
  33557. }
  33558. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  33559. shadowGenerator.useBlurExponentialShadowMap = true;
  33560. }
  33561. if (parsedShadowGenerator.depthScale) {
  33562. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  33563. }
  33564. if (parsedShadowGenerator.blurScale) {
  33565. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  33566. }
  33567. if (parsedShadowGenerator.blurBoxOffset) {
  33568. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  33569. }
  33570. if (parsedShadowGenerator.useKernelBlur) {
  33571. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  33572. }
  33573. if (parsedShadowGenerator.blurKernel) {
  33574. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  33575. }
  33576. if (parsedShadowGenerator.bias !== undefined) {
  33577. shadowGenerator.bias = parsedShadowGenerator.bias;
  33578. }
  33579. if (parsedShadowGenerator.darkness) {
  33580. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  33581. }
  33582. if (parsedShadowGenerator.transparencyShadow) {
  33583. shadowGenerator.setTransparencyShadow(true);
  33584. }
  33585. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  33586. return shadowGenerator;
  33587. };
  33588. return ShadowGenerator;
  33589. }());
  33590. ShadowGenerator._FILTER_NONE = 0;
  33591. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  33592. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  33593. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  33594. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  33595. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  33596. BABYLON.ShadowGenerator = ShadowGenerator;
  33597. })(BABYLON || (BABYLON = {}));
  33598. //# sourceMappingURL=babylon.shadowGenerator.js.map
  33599. var BABYLON;
  33600. (function (BABYLON) {
  33601. var ShadowLight = (function (_super) {
  33602. __extends(ShadowLight, _super);
  33603. function ShadowLight() {
  33604. var _this = _super !== null && _super.apply(this, arguments) || this;
  33605. _this._needProjectionMatrixCompute = true;
  33606. return _this;
  33607. }
  33608. Object.defineProperty(ShadowLight.prototype, "direction", {
  33609. get: function () {
  33610. return this._direction;
  33611. },
  33612. set: function (value) {
  33613. this._direction = value;
  33614. },
  33615. enumerable: true,
  33616. configurable: true
  33617. });
  33618. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  33619. get: function () {
  33620. return this._shadowMinZ;
  33621. },
  33622. set: function (value) {
  33623. this._shadowMinZ = value;
  33624. this.forceProjectionMatrixCompute();
  33625. },
  33626. enumerable: true,
  33627. configurable: true
  33628. });
  33629. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  33630. get: function () {
  33631. return this._shadowMaxZ;
  33632. },
  33633. set: function (value) {
  33634. this._shadowMaxZ = value;
  33635. this.forceProjectionMatrixCompute();
  33636. },
  33637. enumerable: true,
  33638. configurable: true
  33639. });
  33640. /**
  33641. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  33642. */
  33643. ShadowLight.prototype.computeTransformedInformation = function () {
  33644. if (this.parent && this.parent.getWorldMatrix) {
  33645. if (!this.transformedPosition) {
  33646. this.transformedPosition = BABYLON.Vector3.Zero();
  33647. }
  33648. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  33649. // In case the direction is present.
  33650. if (this.direction) {
  33651. if (!this.transformedDirection) {
  33652. this.transformedDirection = BABYLON.Vector3.Zero();
  33653. }
  33654. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  33655. }
  33656. return true;
  33657. }
  33658. return false;
  33659. };
  33660. /**
  33661. * Return the depth scale used for the shadow map.
  33662. */
  33663. ShadowLight.prototype.getDepthScale = function () {
  33664. return 50.0;
  33665. };
  33666. /**
  33667. * Returns the light direction (Vector3) for any passed face index.
  33668. */
  33669. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  33670. return this.transformedDirection ? this.transformedDirection : this.direction;
  33671. };
  33672. /**
  33673. * Returns the DirectionalLight absolute position in the World.
  33674. */
  33675. ShadowLight.prototype.getAbsolutePosition = function () {
  33676. return this.transformedPosition ? this.transformedPosition : this.position;
  33677. };
  33678. /**
  33679. * Sets the DirectionalLight direction toward the passed target (Vector3).
  33680. * Returns the updated DirectionalLight direction (Vector3).
  33681. */
  33682. ShadowLight.prototype.setDirectionToTarget = function (target) {
  33683. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  33684. return this.direction;
  33685. };
  33686. /**
  33687. * Returns the light rotation (Vector3).
  33688. */
  33689. ShadowLight.prototype.getRotation = function () {
  33690. this.direction.normalize();
  33691. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  33692. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  33693. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  33694. };
  33695. /**
  33696. * Boolean : false by default.
  33697. */
  33698. ShadowLight.prototype.needCube = function () {
  33699. return false;
  33700. };
  33701. /**
  33702. * Specifies wether or not the projection matrix should be recomputed this frame.
  33703. */
  33704. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  33705. return this._needProjectionMatrixCompute;
  33706. };
  33707. /**
  33708. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  33709. */
  33710. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  33711. this._needProjectionMatrixCompute = true;
  33712. };
  33713. /**
  33714. * Get the world matrix of the sahdow lights.
  33715. */
  33716. ShadowLight.prototype._getWorldMatrix = function () {
  33717. if (!this._worldMatrix) {
  33718. this._worldMatrix = BABYLON.Matrix.Identity();
  33719. }
  33720. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  33721. return this._worldMatrix;
  33722. };
  33723. /**
  33724. * Gets the minZ used for shadow according to both the scene and the light.
  33725. * @param activeCamera
  33726. */
  33727. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  33728. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  33729. };
  33730. /**
  33731. * Gets the maxZ used for shadow according to both the scene and the light.
  33732. * @param activeCamera
  33733. */
  33734. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  33735. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  33736. };
  33737. /**
  33738. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  33739. * Returns the light.
  33740. */
  33741. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  33742. if (this.customProjectionMatrixBuilder) {
  33743. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  33744. }
  33745. else {
  33746. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  33747. }
  33748. return this;
  33749. };
  33750. return ShadowLight;
  33751. }(BABYLON.Light));
  33752. __decorate([
  33753. BABYLON.serializeAsVector3()
  33754. ], ShadowLight.prototype, "position", void 0);
  33755. __decorate([
  33756. BABYLON.serializeAsVector3()
  33757. ], ShadowLight.prototype, "direction", null);
  33758. __decorate([
  33759. BABYLON.serialize()
  33760. ], ShadowLight.prototype, "shadowMinZ", null);
  33761. __decorate([
  33762. BABYLON.serialize()
  33763. ], ShadowLight.prototype, "shadowMaxZ", null);
  33764. BABYLON.ShadowLight = ShadowLight;
  33765. })(BABYLON || (BABYLON = {}));
  33766. //# sourceMappingURL=babylon.shadowLight.js.map
  33767. var BABYLON;
  33768. (function (BABYLON) {
  33769. var PointLight = (function (_super) {
  33770. __extends(PointLight, _super);
  33771. /**
  33772. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  33773. * A PointLight emits the light in every direction.
  33774. * It can cast shadows.
  33775. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  33776. * ```javascript
  33777. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  33778. * ```
  33779. * Documentation : http://doc.babylonjs.com/tutorials/lights
  33780. */
  33781. function PointLight(name, position, scene) {
  33782. var _this = _super.call(this, name, scene) || this;
  33783. _this._shadowAngle = Math.PI / 2;
  33784. _this.position = position;
  33785. return _this;
  33786. }
  33787. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  33788. /**
  33789. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  33790. * This specifies what angle the shadow will use to be created.
  33791. *
  33792. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  33793. */
  33794. get: function () {
  33795. return this._shadowAngle;
  33796. },
  33797. /**
  33798. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  33799. * This specifies what angle the shadow will use to be created.
  33800. *
  33801. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  33802. */
  33803. set: function (value) {
  33804. this._shadowAngle = value;
  33805. this.forceProjectionMatrixCompute();
  33806. },
  33807. enumerable: true,
  33808. configurable: true
  33809. });
  33810. Object.defineProperty(PointLight.prototype, "direction", {
  33811. get: function () {
  33812. return this._direction;
  33813. },
  33814. /**
  33815. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  33816. */
  33817. set: function (value) {
  33818. var previousNeedCube = this.needCube();
  33819. this._direction = value;
  33820. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  33821. this._shadowGenerator.recreateShadowMap();
  33822. }
  33823. },
  33824. enumerable: true,
  33825. configurable: true
  33826. });
  33827. /**
  33828. * Returns the string "PointLight"
  33829. */
  33830. PointLight.prototype.getClassName = function () {
  33831. return "PointLight";
  33832. };
  33833. /**
  33834. * Returns the integer 0.
  33835. */
  33836. PointLight.prototype.getTypeID = function () {
  33837. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  33838. };
  33839. /**
  33840. * Specifies wether or not the shadowmap should be a cube texture.
  33841. */
  33842. PointLight.prototype.needCube = function () {
  33843. return !this.direction;
  33844. };
  33845. /**
  33846. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  33847. */
  33848. PointLight.prototype.getShadowDirection = function (faceIndex) {
  33849. if (this.direction) {
  33850. return _super.prototype.getShadowDirection.call(this, faceIndex);
  33851. }
  33852. else {
  33853. switch (faceIndex) {
  33854. case 0:
  33855. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  33856. case 1:
  33857. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  33858. case 2:
  33859. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  33860. case 3:
  33861. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  33862. case 4:
  33863. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  33864. case 5:
  33865. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  33866. }
  33867. }
  33868. return BABYLON.Vector3.Zero();
  33869. };
  33870. /**
  33871. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  33872. * - fov = PI / 2
  33873. * - aspect ratio : 1.0
  33874. * - z-near and far equal to the active camera minZ and maxZ.
  33875. * Returns the PointLight.
  33876. */
  33877. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  33878. var activeCamera = this.getScene().activeCamera;
  33879. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  33880. };
  33881. PointLight.prototype._buildUniformLayout = function () {
  33882. this._uniformBuffer.addUniform("vLightData", 4);
  33883. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  33884. this._uniformBuffer.addUniform("vLightSpecular", 3);
  33885. this._uniformBuffer.addUniform("shadowsInfo", 3);
  33886. this._uniformBuffer.addUniform("depthValues", 2);
  33887. this._uniformBuffer.create();
  33888. };
  33889. /**
  33890. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  33891. * Returns the PointLight.
  33892. */
  33893. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  33894. if (this.computeTransformedInformation()) {
  33895. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  33896. return this;
  33897. }
  33898. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  33899. return this;
  33900. };
  33901. return PointLight;
  33902. }(BABYLON.ShadowLight));
  33903. __decorate([
  33904. BABYLON.serialize()
  33905. ], PointLight.prototype, "shadowAngle", null);
  33906. BABYLON.PointLight = PointLight;
  33907. })(BABYLON || (BABYLON = {}));
  33908. //# sourceMappingURL=babylon.pointLight.js.map
  33909. /// <reference path="babylon.light.ts" />
  33910. var BABYLON;
  33911. (function (BABYLON) {
  33912. var DirectionalLight = (function (_super) {
  33913. __extends(DirectionalLight, _super);
  33914. /**
  33915. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  33916. * The directional light is emitted from everywhere in the given direction.
  33917. * It can cast shawdows.
  33918. * Documentation : http://doc.babylonjs.com/tutorials/lights
  33919. */
  33920. function DirectionalLight(name, direction, scene) {
  33921. var _this = _super.call(this, name, scene) || this;
  33922. _this._shadowFrustumSize = 0;
  33923. _this._shadowOrthoScale = 0.5;
  33924. _this.autoUpdateExtends = true;
  33925. // Cache
  33926. _this._orthoLeft = Number.MAX_VALUE;
  33927. _this._orthoRight = Number.MIN_VALUE;
  33928. _this._orthoTop = Number.MIN_VALUE;
  33929. _this._orthoBottom = Number.MAX_VALUE;
  33930. _this.position = direction.scale(-1.0);
  33931. _this.direction = direction;
  33932. return _this;
  33933. }
  33934. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  33935. /**
  33936. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  33937. */
  33938. get: function () {
  33939. return this._shadowFrustumSize;
  33940. },
  33941. /**
  33942. * Specifies a fix frustum size for the shadow generation.
  33943. */
  33944. set: function (value) {
  33945. this._shadowFrustumSize = value;
  33946. this.forceProjectionMatrixCompute();
  33947. },
  33948. enumerable: true,
  33949. configurable: true
  33950. });
  33951. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  33952. get: function () {
  33953. return this._shadowOrthoScale;
  33954. },
  33955. set: function (value) {
  33956. this._shadowOrthoScale = value;
  33957. this.forceProjectionMatrixCompute();
  33958. },
  33959. enumerable: true,
  33960. configurable: true
  33961. });
  33962. /**
  33963. * Returns the string "DirectionalLight".
  33964. */
  33965. DirectionalLight.prototype.getClassName = function () {
  33966. return "DirectionalLight";
  33967. };
  33968. /**
  33969. * Returns the integer 1.
  33970. */
  33971. DirectionalLight.prototype.getTypeID = function () {
  33972. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  33973. };
  33974. /**
  33975. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  33976. * Returns the DirectionalLight Shadow projection matrix.
  33977. */
  33978. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  33979. if (this.shadowFrustumSize > 0) {
  33980. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  33981. }
  33982. else {
  33983. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  33984. }
  33985. };
  33986. /**
  33987. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  33988. * Returns the DirectionalLight Shadow projection matrix.
  33989. */
  33990. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  33991. var activeCamera = this.getScene().activeCamera;
  33992. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  33993. };
  33994. /**
  33995. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  33996. * Returns the DirectionalLight Shadow projection matrix.
  33997. */
  33998. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  33999. var activeCamera = this.getScene().activeCamera;
  34000. // Check extends
  34001. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  34002. var tempVector3 = BABYLON.Vector3.Zero();
  34003. this._orthoLeft = Number.MAX_VALUE;
  34004. this._orthoRight = Number.MIN_VALUE;
  34005. this._orthoTop = Number.MIN_VALUE;
  34006. this._orthoBottom = Number.MAX_VALUE;
  34007. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  34008. var mesh = renderList[meshIndex];
  34009. if (!mesh) {
  34010. continue;
  34011. }
  34012. var boundingInfo = mesh.getBoundingInfo();
  34013. if (!boundingInfo) {
  34014. continue;
  34015. }
  34016. var boundingBox = boundingInfo.boundingBox;
  34017. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  34018. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  34019. if (tempVector3.x < this._orthoLeft)
  34020. this._orthoLeft = tempVector3.x;
  34021. if (tempVector3.y < this._orthoBottom)
  34022. this._orthoBottom = tempVector3.y;
  34023. if (tempVector3.x > this._orthoRight)
  34024. this._orthoRight = tempVector3.x;
  34025. if (tempVector3.y > this._orthoTop)
  34026. this._orthoTop = tempVector3.y;
  34027. }
  34028. }
  34029. }
  34030. var xOffset = this._orthoRight - this._orthoLeft;
  34031. var yOffset = this._orthoTop - this._orthoBottom;
  34032. 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);
  34033. };
  34034. DirectionalLight.prototype._buildUniformLayout = function () {
  34035. this._uniformBuffer.addUniform("vLightData", 4);
  34036. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  34037. this._uniformBuffer.addUniform("vLightSpecular", 3);
  34038. this._uniformBuffer.addUniform("shadowsInfo", 3);
  34039. this._uniformBuffer.addUniform("depthValues", 2);
  34040. this._uniformBuffer.create();
  34041. };
  34042. /**
  34043. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  34044. * Returns the DirectionalLight.
  34045. */
  34046. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  34047. if (this.computeTransformedInformation()) {
  34048. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  34049. return this;
  34050. }
  34051. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  34052. return this;
  34053. };
  34054. /**
  34055. * Gets the minZ used for shadow according to both the scene and the light.
  34056. *
  34057. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  34058. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  34059. * @param activeCamera
  34060. */
  34061. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  34062. return 1;
  34063. };
  34064. /**
  34065. * Gets the maxZ used for shadow according to both the scene and the light.
  34066. *
  34067. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  34068. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  34069. * @param activeCamera
  34070. */
  34071. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  34072. return 1;
  34073. };
  34074. return DirectionalLight;
  34075. }(BABYLON.ShadowLight));
  34076. __decorate([
  34077. BABYLON.serialize()
  34078. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  34079. __decorate([
  34080. BABYLON.serialize()
  34081. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  34082. __decorate([
  34083. BABYLON.serialize()
  34084. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  34085. BABYLON.DirectionalLight = DirectionalLight;
  34086. })(BABYLON || (BABYLON = {}));
  34087. //# sourceMappingURL=babylon.directionalLight.js.map
  34088. var BABYLON;
  34089. (function (BABYLON) {
  34090. var SpotLight = (function (_super) {
  34091. __extends(SpotLight, _super);
  34092. /**
  34093. * Creates a SpotLight object in the scene with the passed parameters :
  34094. * - `position` (Vector3) is the initial SpotLight position,
  34095. * - `direction` (Vector3) is the initial SpotLight direction,
  34096. * - `angle` (float, in radians) is the spot light cone angle,
  34097. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  34098. * A spot light is a simply light oriented cone.
  34099. * It can cast shadows.
  34100. * Documentation : http://doc.babylonjs.com/tutorials/lights
  34101. */
  34102. function SpotLight(name, position, direction, angle, exponent, scene) {
  34103. var _this = _super.call(this, name, scene) || this;
  34104. _this.position = position;
  34105. _this.direction = direction;
  34106. _this.angle = angle;
  34107. _this.exponent = exponent;
  34108. return _this;
  34109. }
  34110. Object.defineProperty(SpotLight.prototype, "angle", {
  34111. get: function () {
  34112. return this._angle;
  34113. },
  34114. set: function (value) {
  34115. this._angle = value;
  34116. this.forceProjectionMatrixCompute();
  34117. },
  34118. enumerable: true,
  34119. configurable: true
  34120. });
  34121. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  34122. get: function () {
  34123. return this._shadowAngleScale;
  34124. },
  34125. /**
  34126. * Allows scaling the angle of the light for shadow generation only.
  34127. */
  34128. set: function (value) {
  34129. this._shadowAngleScale = value;
  34130. this.forceProjectionMatrixCompute();
  34131. },
  34132. enumerable: true,
  34133. configurable: true
  34134. });
  34135. /**
  34136. * Returns the string "SpotLight".
  34137. */
  34138. SpotLight.prototype.getClassName = function () {
  34139. return "SpotLight";
  34140. };
  34141. /**
  34142. * Returns the integer 2.
  34143. */
  34144. SpotLight.prototype.getTypeID = function () {
  34145. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  34146. };
  34147. /**
  34148. * 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.
  34149. * Returns the SpotLight.
  34150. */
  34151. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  34152. var activeCamera = this.getScene().activeCamera;
  34153. this._shadowAngleScale = this._shadowAngleScale || 1;
  34154. var angle = this._shadowAngleScale * this._angle;
  34155. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  34156. };
  34157. SpotLight.prototype._buildUniformLayout = function () {
  34158. this._uniformBuffer.addUniform("vLightData", 4);
  34159. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  34160. this._uniformBuffer.addUniform("vLightSpecular", 3);
  34161. this._uniformBuffer.addUniform("vLightDirection", 3);
  34162. this._uniformBuffer.addUniform("shadowsInfo", 3);
  34163. this._uniformBuffer.addUniform("depthValues", 2);
  34164. this._uniformBuffer.create();
  34165. };
  34166. /**
  34167. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  34168. * Return the SpotLight.
  34169. */
  34170. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  34171. var normalizeDirection;
  34172. if (this.computeTransformedInformation()) {
  34173. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  34174. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  34175. }
  34176. else {
  34177. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  34178. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  34179. }
  34180. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  34181. return this;
  34182. };
  34183. return SpotLight;
  34184. }(BABYLON.ShadowLight));
  34185. __decorate([
  34186. BABYLON.serialize()
  34187. ], SpotLight.prototype, "angle", null);
  34188. __decorate([
  34189. BABYLON.serialize()
  34190. /**
  34191. * Allows scaling the angle of the light for shadow generation only.
  34192. */
  34193. ], SpotLight.prototype, "shadowAngleScale", null);
  34194. __decorate([
  34195. BABYLON.serialize()
  34196. ], SpotLight.prototype, "exponent", void 0);
  34197. BABYLON.SpotLight = SpotLight;
  34198. })(BABYLON || (BABYLON = {}));
  34199. //# sourceMappingURL=babylon.spotLight.js.map
  34200. var BABYLON;
  34201. (function (BABYLON) {
  34202. var MultiMaterial = (function (_super) {
  34203. __extends(MultiMaterial, _super);
  34204. function MultiMaterial(name, scene) {
  34205. var _this = _super.call(this, name, scene, true) || this;
  34206. _this.subMaterials = new Array();
  34207. scene.multiMaterials.push(_this);
  34208. return _this;
  34209. }
  34210. // Properties
  34211. MultiMaterial.prototype.getSubMaterial = function (index) {
  34212. if (index < 0 || index >= this.subMaterials.length) {
  34213. return this.getScene().defaultMaterial;
  34214. }
  34215. return this.subMaterials[index];
  34216. };
  34217. // Methods
  34218. MultiMaterial.prototype.getClassName = function () {
  34219. return "MultiMaterial";
  34220. };
  34221. MultiMaterial.prototype.isReady = function (mesh) {
  34222. for (var index = 0; index < this.subMaterials.length; index++) {
  34223. var subMaterial = this.subMaterials[index];
  34224. if (subMaterial) {
  34225. if (!this.subMaterials[index].isReady(mesh)) {
  34226. return false;
  34227. }
  34228. }
  34229. }
  34230. return true;
  34231. };
  34232. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  34233. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  34234. for (var index = 0; index < this.subMaterials.length; index++) {
  34235. var subMaterial = null;
  34236. if (cloneChildren) {
  34237. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  34238. }
  34239. else {
  34240. subMaterial = this.subMaterials[index];
  34241. }
  34242. newMultiMaterial.subMaterials.push(subMaterial);
  34243. }
  34244. return newMultiMaterial;
  34245. };
  34246. MultiMaterial.prototype.serialize = function () {
  34247. var serializationObject = {};
  34248. serializationObject.name = this.name;
  34249. serializationObject.id = this.id;
  34250. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34251. serializationObject.materials = [];
  34252. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  34253. var subMat = this.subMaterials[matIndex];
  34254. if (subMat) {
  34255. serializationObject.materials.push(subMat.id);
  34256. }
  34257. else {
  34258. serializationObject.materials.push(null);
  34259. }
  34260. }
  34261. return serializationObject;
  34262. };
  34263. return MultiMaterial;
  34264. }(BABYLON.Material));
  34265. BABYLON.MultiMaterial = MultiMaterial;
  34266. })(BABYLON || (BABYLON = {}));
  34267. //# sourceMappingURL=babylon.multiMaterial.js.map
  34268. var BABYLON;
  34269. (function (BABYLON) {
  34270. var PBRMaterialDefines = (function (_super) {
  34271. __extends(PBRMaterialDefines, _super);
  34272. function PBRMaterialDefines() {
  34273. var _this = _super.call(this) || this;
  34274. _this.PBR = true;
  34275. _this.ALBEDO = false;
  34276. _this.AMBIENT = false;
  34277. _this.AMBIENTINGRAYSCALE = false;
  34278. _this.OPACITY = false;
  34279. _this.OPACITYRGB = false;
  34280. _this.REFLECTION = false;
  34281. _this.EMISSIVE = false;
  34282. _this.REFLECTIVITY = false;
  34283. _this.BUMP = false;
  34284. _this.PARALLAX = false;
  34285. _this.PARALLAXOCCLUSION = false;
  34286. _this.SPECULAROVERALPHA = false;
  34287. _this.CLIPPLANE = false;
  34288. _this.ALPHATEST = false;
  34289. _this.ALPHAFROMALBEDO = false;
  34290. _this.POINTSIZE = false;
  34291. _this.FOG = false;
  34292. _this.SPECULARTERM = false;
  34293. _this.OPACITYFRESNEL = false;
  34294. _this.EMISSIVEFRESNEL = false;
  34295. _this.FRESNEL = false;
  34296. _this.NORMAL = false;
  34297. _this.TANGENT = false;
  34298. _this.UV1 = false;
  34299. _this.UV2 = false;
  34300. _this.VERTEXCOLOR = false;
  34301. _this.VERTEXALPHA = false;
  34302. _this.NUM_BONE_INFLUENCERS = 0;
  34303. _this.BonesPerMesh = 0;
  34304. _this.INSTANCES = false;
  34305. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  34306. _this.MICROSURFACEAUTOMATIC = false;
  34307. _this.EMISSIVEASILLUMINATION = false;
  34308. _this.LIGHTMAP = false;
  34309. _this.USELIGHTMAPASSHADOWMAP = false;
  34310. _this.REFLECTIONMAP_3D = false;
  34311. _this.REFLECTIONMAP_SPHERICAL = false;
  34312. _this.REFLECTIONMAP_PLANAR = false;
  34313. _this.REFLECTIONMAP_CUBIC = false;
  34314. _this.REFLECTIONMAP_PROJECTION = false;
  34315. _this.REFLECTIONMAP_SKYBOX = false;
  34316. _this.REFLECTIONMAP_EXPLICIT = false;
  34317. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34318. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34319. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34320. _this.INVERTCUBICMAP = false;
  34321. _this.LOGARITHMICDEPTH = false;
  34322. _this.CAMERATONEMAP = false;
  34323. _this.CAMERACONTRAST = false;
  34324. _this.CAMERACOLORGRADING = false;
  34325. _this.CAMERACOLORCURVES = false;
  34326. _this.USESPHERICALFROMREFLECTIONMAP = false;
  34327. _this.REFRACTION = false;
  34328. _this.REFRACTIONMAP_3D = false;
  34329. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  34330. _this.REFRACTIONMAPINLINEARSPACE = false;
  34331. _this.LODBASEDMICROSFURACE = false;
  34332. _this.USEPHYSICALLIGHTFALLOFF = false;
  34333. _this.RADIANCEOVERALPHA = false;
  34334. _this.USEPMREMREFLECTION = false;
  34335. _this.USEPMREMREFRACTION = false;
  34336. _this.INVERTNORMALMAPX = false;
  34337. _this.INVERTNORMALMAPY = false;
  34338. _this.TWOSIDEDLIGHTING = false;
  34339. _this.SHADOWFLOAT = false;
  34340. _this.NORMALXYSCALE = true;
  34341. _this.USERIGHTHANDEDSYSTEM = false;
  34342. _this.METALLICWORKFLOW = false;
  34343. _this.METALLICMAP = false;
  34344. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  34345. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  34346. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  34347. _this.AOSTOREINMETALMAPRED = false;
  34348. _this.MICROSURFACEMAP = false;
  34349. _this.MORPHTARGETS = false;
  34350. _this.MORPHTARGETS_NORMAL = false;
  34351. _this.MORPHTARGETS_TANGENT = false;
  34352. _this.NUM_MORPH_INFLUENCERS = 0;
  34353. _this.ALPHATESTVALUE = 0.4;
  34354. _this.LDROUTPUT = true;
  34355. _this.rebuild();
  34356. return _this;
  34357. }
  34358. PBRMaterialDefines.prototype.reset = function () {
  34359. _super.prototype.reset.call(this);
  34360. this.ALPHATESTVALUE = 0.4;
  34361. this.PBR = true;
  34362. };
  34363. return PBRMaterialDefines;
  34364. }(BABYLON.MaterialDefines));
  34365. /**
  34366. * The Physically based material base class of BJS.
  34367. *
  34368. * This offers the main features of a standard PBR material.
  34369. * For more information, please refer to the documentation :
  34370. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  34371. */
  34372. var PBRBaseMaterial = (function (_super) {
  34373. __extends(PBRBaseMaterial, _super);
  34374. /**
  34375. * Instantiates a new PBRMaterial instance.
  34376. *
  34377. * @param name The material name
  34378. * @param scene The scene the material will be use in.
  34379. */
  34380. function PBRBaseMaterial(name, scene) {
  34381. var _this = _super.call(this, name, scene) || this;
  34382. /**
  34383. * Intensity of the direct lights e.g. the four lights available in your scene.
  34384. * This impacts both the direct diffuse and specular highlights.
  34385. */
  34386. _this._directIntensity = 1.0;
  34387. /**
  34388. * Intensity of the emissive part of the material.
  34389. * This helps controlling the emissive effect without modifying the emissive color.
  34390. */
  34391. _this._emissiveIntensity = 1.0;
  34392. /**
  34393. * Intensity of the environment e.g. how much the environment will light the object
  34394. * either through harmonics for rough material or through the refelction for shiny ones.
  34395. */
  34396. _this._environmentIntensity = 1.0;
  34397. /**
  34398. * This is a special control allowing the reduction of the specular highlights coming from the
  34399. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  34400. */
  34401. _this._specularIntensity = 1.0;
  34402. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  34403. /**
  34404. * Debug Control allowing disabling the bump map on this material.
  34405. */
  34406. _this._disableBumpMap = false;
  34407. /**
  34408. * The camera exposure used on this material.
  34409. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  34410. * This corresponds to a photographic exposure.
  34411. */
  34412. _this._cameraExposure = 1.0;
  34413. /**
  34414. * The camera contrast used on this material.
  34415. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  34416. */
  34417. _this._cameraContrast = 1.0;
  34418. /**
  34419. * Color Grading 2D Lookup Texture.
  34420. * This allows special effects like sepia, black and white to sixties rendering style.
  34421. */
  34422. _this._cameraColorGradingTexture = null;
  34423. /**
  34424. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34425. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34426. * 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;
  34427. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34428. */
  34429. _this._cameraColorCurves = null;
  34430. _this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  34431. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  34432. /**
  34433. * AKA Occlusion Texture Intensity in other nomenclature.
  34434. */
  34435. _this._ambientTextureStrength = 1.0;
  34436. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  34437. /**
  34438. * AKA Diffuse Color in other nomenclature.
  34439. */
  34440. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  34441. /**
  34442. * AKA Specular Color in other nomenclature.
  34443. */
  34444. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  34445. _this._reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  34446. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  34447. /**
  34448. * AKA Glossiness in other nomenclature.
  34449. */
  34450. _this._microSurface = 0.9;
  34451. /**
  34452. * source material index of refraction (IOR)' / 'destination material IOR.
  34453. */
  34454. _this._indexOfRefraction = 0.66;
  34455. /**
  34456. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  34457. */
  34458. _this._invertRefractionY = false;
  34459. /**
  34460. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  34461. * Materials half opaque for instance using refraction could benefit from this control.
  34462. */
  34463. _this._linkRefractionWithTransparency = false;
  34464. _this._useLightmapAsShadowmap = false;
  34465. /**
  34466. * In this mode, the emissive informtaion will always be added to the lighting once.
  34467. * A light for instance can be thought as emissive.
  34468. */
  34469. _this._useEmissiveAsIllumination = false;
  34470. /**
  34471. * Secifies that the alpha is coming form the albedo channel alpha channel.
  34472. */
  34473. _this._useAlphaFromAlbedoTexture = false;
  34474. /**
  34475. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  34476. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  34477. */
  34478. _this._useSpecularOverAlpha = true;
  34479. /**
  34480. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  34481. */
  34482. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  34483. /**
  34484. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  34485. */
  34486. _this._useRoughnessFromMetallicTextureAlpha = true;
  34487. /**
  34488. * Specifies if the metallic texture contains the roughness information in its green channel.
  34489. */
  34490. _this._useRoughnessFromMetallicTextureGreen = false;
  34491. /**
  34492. * Specifies if the metallic texture contains the metallness information in its blue channel.
  34493. */
  34494. _this._useMetallnessFromMetallicTextureBlue = false;
  34495. /**
  34496. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  34497. */
  34498. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  34499. /**
  34500. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  34501. */
  34502. _this._useAmbientInGrayScale = false;
  34503. /**
  34504. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  34505. * The material will try to infer what glossiness each pixel should be.
  34506. */
  34507. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  34508. /**
  34509. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  34510. * the creation of the material.
  34511. */
  34512. _this._useScalarInLinearSpace = false;
  34513. /**
  34514. * BJS is using an harcoded light falloff based on a manually sets up range.
  34515. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  34516. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  34517. */
  34518. _this._usePhysicalLightFalloff = true;
  34519. /**
  34520. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  34521. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  34522. */
  34523. _this._useRadianceOverAlpha = true;
  34524. /**
  34525. * Allows using the bump map in parallax mode.
  34526. */
  34527. _this._useParallax = false;
  34528. /**
  34529. * Allows using the bump map in parallax occlusion mode.
  34530. */
  34531. _this._useParallaxOcclusion = false;
  34532. /**
  34533. * Controls the scale bias of the parallax mode.
  34534. */
  34535. _this._parallaxScaleBias = 0.05;
  34536. /**
  34537. * If sets to true, disables all the lights affecting the material.
  34538. */
  34539. _this._disableLighting = false;
  34540. /**
  34541. * Number of Simultaneous lights allowed on the material.
  34542. */
  34543. _this._maxSimultaneousLights = 4;
  34544. /**
  34545. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  34546. */
  34547. _this._invertNormalMapX = false;
  34548. /**
  34549. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  34550. */
  34551. _this._invertNormalMapY = false;
  34552. /**
  34553. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  34554. */
  34555. _this._twoSidedLighting = false;
  34556. /**
  34557. * Defines the alpha limits in alpha test mode.
  34558. */
  34559. _this._alphaCutOff = 0.4;
  34560. /**
  34561. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  34562. */
  34563. _this._forceAlphaTest = false;
  34564. /**
  34565. * If false, it allows the output of the shader to be in hdr space (e.g. more than one) which is useful
  34566. * in combination of post process in float or half float mode.
  34567. */
  34568. _this._ldrOutput = true;
  34569. _this._renderTargets = new BABYLON.SmartArray(16);
  34570. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  34571. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  34572. _this._tempColor = new BABYLON.Color3();
  34573. _this.getRenderTargetTextures = function () {
  34574. _this._renderTargets.reset();
  34575. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  34576. _this._renderTargets.push(_this._reflectionTexture);
  34577. }
  34578. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  34579. _this._renderTargets.push(_this._refractionTexture);
  34580. }
  34581. return _this._renderTargets;
  34582. };
  34583. return _this;
  34584. }
  34585. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  34586. get: function () {
  34587. return this._useLogarithmicDepth;
  34588. },
  34589. set: function (value) {
  34590. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  34591. },
  34592. enumerable: true,
  34593. configurable: true
  34594. });
  34595. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  34596. if (this._linkRefractionWithTransparency) {
  34597. return false;
  34598. }
  34599. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  34600. };
  34601. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  34602. if (this._linkRefractionWithTransparency) {
  34603. return false;
  34604. }
  34605. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  34606. };
  34607. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  34608. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  34609. };
  34610. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  34611. return this._albedoTexture;
  34612. };
  34613. PBRBaseMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  34614. BABYLON.PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this._useScalarInLinearSpace);
  34615. };
  34616. PBRBaseMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  34617. if (!useScalarInLinear) {
  34618. color.toLinearSpaceToRef(ref);
  34619. }
  34620. else {
  34621. ref.r = color.r;
  34622. ref.g = color.g;
  34623. ref.b = color.b;
  34624. }
  34625. };
  34626. PBRBaseMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  34627. var lightIndex = 0;
  34628. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  34629. var light = _a[_i];
  34630. var useUbo = light._uniformBuffer.useUbo;
  34631. var scaledIntensity = light.getScaledIntensity();
  34632. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  34633. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  34634. // GAMMA CORRECTION.
  34635. this.convertColorToLinearSpaceToRef(light.diffuse, BABYLON.PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  34636. BABYLON.PBRMaterial._scaledAlbedo.scaleToRef(scaledIntensity, BABYLON.PBRMaterial._scaledAlbedo);
  34637. light._uniformBuffer.updateColor4(useUbo ? "vLightDiffuse" : "vLightDiffuse" + lightIndex, BABYLON.PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  34638. if (defines["SPECULARTERM"]) {
  34639. this.convertColorToLinearSpaceToRef(light.specular, BABYLON.PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  34640. BABYLON.PBRMaterial._scaledReflectivity.scaleToRef(scaledIntensity, BABYLON.PBRMaterial._scaledReflectivity);
  34641. light._uniformBuffer.updateColor3(useUbo ? "vLightSpecular" : "vLightSpecular" + lightIndex, BABYLON.PBRMaterial._scaledReflectivity);
  34642. }
  34643. // Shadows
  34644. if (scene.shadowsEnabled) {
  34645. BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  34646. }
  34647. light._uniformBuffer.update();
  34648. lightIndex++;
  34649. if (lightIndex === maxSimultaneousLights)
  34650. break;
  34651. }
  34652. };
  34653. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34654. if (this.isFrozen) {
  34655. if (this._wasPreviouslyReady) {
  34656. return true;
  34657. }
  34658. }
  34659. if (!subMesh._materialDefines) {
  34660. subMesh._materialDefines = new PBRMaterialDefines();
  34661. }
  34662. var scene = this.getScene();
  34663. var defines = subMesh._materialDefines;
  34664. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  34665. if (defines._renderId === scene.getRenderId()) {
  34666. return true;
  34667. }
  34668. }
  34669. var engine = scene.getEngine();
  34670. // Lights
  34671. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  34672. defines._needNormals = true;
  34673. // Textures
  34674. if (defines._areTexturesDirty) {
  34675. defines._needUVs = false;
  34676. if (scene.texturesEnabled) {
  34677. if (scene.getEngine().getCaps().textureLOD) {
  34678. defines.LODBASEDMICROSFURACE = true;
  34679. }
  34680. defines.LDROUTPUT = this._ldrOutput;
  34681. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  34682. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  34683. return false;
  34684. }
  34685. defines._needUVs = true;
  34686. defines.ALBEDO = true;
  34687. }
  34688. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  34689. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  34690. return false;
  34691. }
  34692. defines._needUVs = true;
  34693. defines.AMBIENT = true;
  34694. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  34695. }
  34696. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  34697. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  34698. return false;
  34699. }
  34700. defines._needUVs = true;
  34701. defines.OPACITY = true;
  34702. if (this._opacityTexture.getAlphaFromRGB) {
  34703. defines.OPACITYRGB = true;
  34704. }
  34705. }
  34706. var reflectionTexture = this._reflectionTexture || scene.environmentTexture;
  34707. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  34708. if (!reflectionTexture.isReadyOrNotBlocking()) {
  34709. return false;
  34710. }
  34711. defines.REFLECTION = true;
  34712. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  34713. defines.INVERTCUBICMAP = true;
  34714. }
  34715. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  34716. switch (reflectionTexture.coordinatesMode) {
  34717. case BABYLON.Texture.CUBIC_MODE:
  34718. case BABYLON.Texture.INVCUBIC_MODE:
  34719. defines.REFLECTIONMAP_CUBIC = true;
  34720. break;
  34721. case BABYLON.Texture.EXPLICIT_MODE:
  34722. defines.REFLECTIONMAP_EXPLICIT = true;
  34723. break;
  34724. case BABYLON.Texture.PLANAR_MODE:
  34725. defines.REFLECTIONMAP_PLANAR = true;
  34726. break;
  34727. case BABYLON.Texture.PROJECTION_MODE:
  34728. defines.REFLECTIONMAP_PROJECTION = true;
  34729. break;
  34730. case BABYLON.Texture.SKYBOX_MODE:
  34731. defines.REFLECTIONMAP_SKYBOX = true;
  34732. break;
  34733. case BABYLON.Texture.SPHERICAL_MODE:
  34734. defines.REFLECTIONMAP_SPHERICAL = true;
  34735. break;
  34736. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  34737. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  34738. break;
  34739. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  34740. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  34741. break;
  34742. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  34743. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  34744. break;
  34745. }
  34746. if (reflectionTexture instanceof BABYLON.HDRCubeTexture && reflectionTexture) {
  34747. defines.USESPHERICALFROMREFLECTIONMAP = true;
  34748. if (reflectionTexture.isPMREM) {
  34749. defines.USEPMREMREFLECTION = true;
  34750. }
  34751. }
  34752. }
  34753. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  34754. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  34755. return false;
  34756. }
  34757. defines._needUVs = true;
  34758. defines.LIGHTMAP = true;
  34759. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  34760. }
  34761. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  34762. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  34763. return false;
  34764. }
  34765. defines._needUVs = true;
  34766. defines.EMISSIVE = true;
  34767. }
  34768. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  34769. if (this._metallicTexture) {
  34770. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  34771. return false;
  34772. }
  34773. defines._needUVs = true;
  34774. defines.METALLICWORKFLOW = true;
  34775. defines.METALLICMAP = true;
  34776. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  34777. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  34778. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  34779. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  34780. }
  34781. else if (this._reflectivityTexture) {
  34782. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  34783. return false;
  34784. }
  34785. defines._needUVs = true;
  34786. defines.REFLECTIVITY = true;
  34787. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  34788. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  34789. }
  34790. if (this._microSurfaceTexture) {
  34791. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  34792. return false;
  34793. }
  34794. defines._needUVs = true;
  34795. defines.MICROSURFACEMAP = true;
  34796. }
  34797. }
  34798. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  34799. // Bump texure can not be none blocking.
  34800. if (!this._bumpTexture.isReady()) {
  34801. return false;
  34802. }
  34803. defines._needUVs = true;
  34804. defines.BUMP = true;
  34805. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  34806. defines.PARALLAX = true;
  34807. if (this._useParallaxOcclusion) {
  34808. defines.PARALLAXOCCLUSION = true;
  34809. }
  34810. }
  34811. if (this._invertNormalMapX) {
  34812. defines.INVERTNORMALMAPX = true;
  34813. }
  34814. if (this._invertNormalMapY) {
  34815. defines.INVERTNORMALMAPY = true;
  34816. }
  34817. if (scene._mirroredCameraPosition) {
  34818. defines.INVERTNORMALMAPX = !defines.INVERTNORMALMAPX;
  34819. defines.INVERTNORMALMAPY = !defines.INVERTNORMALMAPY;
  34820. }
  34821. defines.USERIGHTHANDEDSYSTEM = scene.useRightHandedSystem;
  34822. }
  34823. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  34824. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  34825. return false;
  34826. }
  34827. defines._needUVs = true;
  34828. defines.REFRACTION = true;
  34829. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  34830. if (this._linkRefractionWithTransparency) {
  34831. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  34832. }
  34833. if (this._refractionTexture instanceof BABYLON.HDRCubeTexture) {
  34834. defines.REFRACTIONMAPINLINEARSPACE = true;
  34835. if (this._refractionTexture.isPMREM) {
  34836. defines.USEPMREMREFRACTION = true;
  34837. }
  34838. }
  34839. }
  34840. if (this._cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  34841. // Color Grading texure can not be none blocking.
  34842. if (!this._cameraColorGradingTexture.isReady()) {
  34843. return false;
  34844. }
  34845. defines.CAMERACOLORGRADING = true;
  34846. }
  34847. if (!this.backFaceCulling && this._twoSidedLighting) {
  34848. defines.TWOSIDEDLIGHTING = true;
  34849. }
  34850. if (this._shouldUseAlphaFromAlbedoTexture()) {
  34851. defines.ALPHAFROMALBEDO = true;
  34852. }
  34853. if (this._useEmissiveAsIllumination) {
  34854. defines.EMISSIVEASILLUMINATION = true;
  34855. }
  34856. if (this._cameraContrast != 1) {
  34857. defines.CAMERACONTRAST = true;
  34858. }
  34859. if (this._cameraExposure != 1) {
  34860. defines.CAMERATONEMAP = true;
  34861. }
  34862. if (this._cameraColorCurves) {
  34863. defines.CAMERACOLORCURVES = true;
  34864. }
  34865. if (this._useSpecularOverAlpha) {
  34866. defines.SPECULAROVERALPHA = true;
  34867. }
  34868. if (this._usePhysicalLightFalloff) {
  34869. defines.USEPHYSICALLIGHTFALLOFF = true;
  34870. }
  34871. if (this._useRadianceOverAlpha) {
  34872. defines.RADIANCEOVERALPHA = true;
  34873. }
  34874. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  34875. defines.METALLICWORKFLOW = true;
  34876. }
  34877. defines.ALPHATESTVALUE = this._alphaCutOff;
  34878. }
  34879. }
  34880. if (defines._areFresnelDirty) {
  34881. if (BABYLON.StandardMaterial.FresnelEnabled) {
  34882. // Fresnel
  34883. if (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled ||
  34884. this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled) {
  34885. if (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled) {
  34886. defines.OPACITYFRESNEL = true;
  34887. }
  34888. if (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled) {
  34889. defines.EMISSIVEFRESNEL = true;
  34890. }
  34891. defines.FRESNEL = true;
  34892. }
  34893. }
  34894. }
  34895. // Misc.
  34896. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  34897. // Values that need to be evaluated on every frame
  34898. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._forceAlphaTest);
  34899. // Attribs
  34900. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  34901. if (mesh) {
  34902. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34903. mesh.createNormals(true);
  34904. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  34905. }
  34906. }
  34907. }
  34908. // Get correct effect
  34909. if (defines.isDirty) {
  34910. defines.markAsProcessed();
  34911. scene.resetCachedMaterial();
  34912. // Fallbacks
  34913. var fallbacks = new BABYLON.EffectFallbacks();
  34914. if (defines.REFLECTION) {
  34915. fallbacks.addFallback(0, "REFLECTION");
  34916. }
  34917. if (defines.REFRACTION) {
  34918. fallbacks.addFallback(0, "REFRACTION");
  34919. }
  34920. if (defines.REFLECTIVITY) {
  34921. fallbacks.addFallback(0, "REFLECTIVITY");
  34922. }
  34923. if (defines.BUMP) {
  34924. fallbacks.addFallback(0, "BUMP");
  34925. }
  34926. if (defines.PARALLAX) {
  34927. fallbacks.addFallback(1, "PARALLAX");
  34928. }
  34929. if (defines.PARALLAXOCCLUSION) {
  34930. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  34931. }
  34932. if (defines.SPECULAROVERALPHA) {
  34933. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  34934. }
  34935. if (defines.FOG) {
  34936. fallbacks.addFallback(1, "FOG");
  34937. }
  34938. if (defines.POINTSIZE) {
  34939. fallbacks.addFallback(0, "POINTSIZE");
  34940. }
  34941. if (defines.LOGARITHMICDEPTH) {
  34942. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  34943. }
  34944. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  34945. if (defines.SPECULARTERM) {
  34946. fallbacks.addFallback(0, "SPECULARTERM");
  34947. }
  34948. if (defines.OPACITYFRESNEL) {
  34949. fallbacks.addFallback(1, "OPACITYFRESNEL");
  34950. }
  34951. if (defines.EMISSIVEFRESNEL) {
  34952. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  34953. }
  34954. if (defines.FRESNEL) {
  34955. fallbacks.addFallback(3, "FRESNEL");
  34956. }
  34957. if (defines.NUM_BONE_INFLUENCERS > 0) {
  34958. fallbacks.addCPUSkinningFallback(0, mesh);
  34959. }
  34960. //Attributes
  34961. var attribs = [BABYLON.VertexBuffer.PositionKind];
  34962. if (defines.NORMAL) {
  34963. attribs.push(BABYLON.VertexBuffer.NormalKind);
  34964. }
  34965. if (defines.TANGENT) {
  34966. attribs.push(BABYLON.VertexBuffer.TangentKind);
  34967. }
  34968. if (defines.UV1) {
  34969. attribs.push(BABYLON.VertexBuffer.UVKind);
  34970. }
  34971. if (defines.UV2) {
  34972. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  34973. }
  34974. if (defines.VERTEXCOLOR) {
  34975. attribs.push(BABYLON.VertexBuffer.ColorKind);
  34976. }
  34977. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  34978. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  34979. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  34980. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  34981. "vFogInfos", "vFogColor", "pointSize",
  34982. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  34983. "mBones",
  34984. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  34985. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  34986. "vLightingIntensity",
  34987. "logarithmicDepthConstant",
  34988. "vSphericalX", "vSphericalY", "vSphericalZ",
  34989. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  34990. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  34991. "vMicrosurfaceTextureLods",
  34992. "vCameraInfos"
  34993. ];
  34994. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "microSurfaceSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  34995. var uniformBuffers = ["Material", "Scene"];
  34996. if (defines.CAMERACOLORCURVES) {
  34997. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  34998. }
  34999. if (defines.CAMERACOLORGRADING) {
  35000. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  35001. }
  35002. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  35003. uniformsNames: uniforms,
  35004. uniformBuffersNames: uniformBuffers,
  35005. samplers: samplers,
  35006. defines: defines,
  35007. maxSimultaneousLights: this._maxSimultaneousLights
  35008. });
  35009. var onCompiled = function (effect) {
  35010. if (this.onCompiled) {
  35011. this.onCompiled(effect);
  35012. }
  35013. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  35014. }.bind(this);
  35015. var join = defines.toString();
  35016. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  35017. attributes: attribs,
  35018. uniformsNames: uniforms,
  35019. uniformBuffersNames: uniformBuffers,
  35020. samplers: samplers,
  35021. defines: join,
  35022. fallbacks: fallbacks,
  35023. onCompiled: onCompiled,
  35024. onError: this.onError,
  35025. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  35026. }, engine), defines);
  35027. this.buildUniformLayout();
  35028. }
  35029. if (!subMesh.effect.isReady()) {
  35030. return false;
  35031. }
  35032. defines._renderId = scene.getRenderId();
  35033. this._wasPreviouslyReady = true;
  35034. return true;
  35035. };
  35036. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  35037. // Order is important !
  35038. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  35039. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  35040. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  35041. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  35042. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  35043. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  35044. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  35045. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  35046. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  35047. this._uniformBuffer.addUniform("vBumpInfos", 3);
  35048. this._uniformBuffer.addUniform("albedoMatrix", 16);
  35049. this._uniformBuffer.addUniform("ambientMatrix", 16);
  35050. this._uniformBuffer.addUniform("opacityMatrix", 16);
  35051. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  35052. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  35053. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  35054. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  35055. this._uniformBuffer.addUniform("bumpMatrix", 16);
  35056. this._uniformBuffer.addUniform("refractionMatrix", 16);
  35057. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  35058. this._uniformBuffer.addUniform("vReflectionColor", 3);
  35059. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  35060. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  35061. this._uniformBuffer.addUniform("vMicrosurfaceTextureLods", 2);
  35062. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  35063. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  35064. this._uniformBuffer.addUniform("opacityParts", 4);
  35065. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  35066. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  35067. this._uniformBuffer.addUniform("pointSize", 1);
  35068. this._uniformBuffer.create();
  35069. };
  35070. PBRBaseMaterial.prototype.unbind = function () {
  35071. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  35072. this._uniformBuffer.setTexture("reflection2DSampler", null);
  35073. }
  35074. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  35075. this._uniformBuffer.setTexture("refraction2DSampler", null);
  35076. }
  35077. _super.prototype.unbind.call(this);
  35078. };
  35079. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  35080. this._activeEffect.setMatrix("world", world);
  35081. };
  35082. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35083. var scene = this.getScene();
  35084. var defines = subMesh._materialDefines;
  35085. if (!defines) {
  35086. return;
  35087. }
  35088. var effect = subMesh.effect;
  35089. this._activeEffect = effect;
  35090. // Matrices
  35091. this.bindOnlyWorldMatrix(world);
  35092. // Bones
  35093. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  35094. if (this._mustRebind(scene, effect, mesh.visibility)) {
  35095. this._uniformBuffer.bindToEffect(effect, "Material");
  35096. this.bindViewProjection(effect);
  35097. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35098. // Fresnel
  35099. if (BABYLON.StandardMaterial.FresnelEnabled) {
  35100. if (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled) {
  35101. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this._opacityFresnelParameters.leftColor.toLuminance(), this._opacityFresnelParameters.rightColor.toLuminance(), this._opacityFresnelParameters.bias), this._opacityFresnelParameters.power);
  35102. }
  35103. if (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled) {
  35104. this._uniformBuffer.updateColor4("emissiveLeftColor", this._emissiveFresnelParameters.leftColor, this._emissiveFresnelParameters.power);
  35105. this._uniformBuffer.updateColor4("emissiveRightColor", this._emissiveFresnelParameters.rightColor, this._emissiveFresnelParameters.bias);
  35106. }
  35107. }
  35108. // Texture uniforms
  35109. if (scene.texturesEnabled) {
  35110. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35111. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  35112. this._uniformBuffer.updateMatrix("albedoMatrix", this._albedoTexture.getTextureMatrix());
  35113. }
  35114. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35115. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  35116. this._uniformBuffer.updateMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  35117. }
  35118. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35119. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35120. this._uniformBuffer.updateMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  35121. }
  35122. var reflectionTexture = this._reflectionTexture || scene.environmentTexture;
  35123. ;
  35124. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35125. this._microsurfaceTextureLods.x = Math.round(Math.log(reflectionTexture.getSize().width) * Math.LOG2E);
  35126. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  35127. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  35128. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  35129. this._activeEffect.setFloat3("vSphericalX", reflectionTexture.sphericalPolynomial.x.x, reflectionTexture.sphericalPolynomial.x.y, reflectionTexture.sphericalPolynomial.x.z);
  35130. this._activeEffect.setFloat3("vSphericalY", reflectionTexture.sphericalPolynomial.y.x, reflectionTexture.sphericalPolynomial.y.y, reflectionTexture.sphericalPolynomial.y.z);
  35131. this._activeEffect.setFloat3("vSphericalZ", reflectionTexture.sphericalPolynomial.z.x, reflectionTexture.sphericalPolynomial.z.y, reflectionTexture.sphericalPolynomial.z.z);
  35132. this._activeEffect.setFloat3("vSphericalXX", reflectionTexture.sphericalPolynomial.xx.x, reflectionTexture.sphericalPolynomial.xx.y, reflectionTexture.sphericalPolynomial.xx.z);
  35133. this._activeEffect.setFloat3("vSphericalYY", reflectionTexture.sphericalPolynomial.yy.x, reflectionTexture.sphericalPolynomial.yy.y, reflectionTexture.sphericalPolynomial.yy.z);
  35134. this._activeEffect.setFloat3("vSphericalZZ", reflectionTexture.sphericalPolynomial.zz.x, reflectionTexture.sphericalPolynomial.zz.y, reflectionTexture.sphericalPolynomial.zz.z);
  35135. this._activeEffect.setFloat3("vSphericalXY", reflectionTexture.sphericalPolynomial.xy.x, reflectionTexture.sphericalPolynomial.xy.y, reflectionTexture.sphericalPolynomial.xy.z);
  35136. this._activeEffect.setFloat3("vSphericalYZ", reflectionTexture.sphericalPolynomial.yz.x, reflectionTexture.sphericalPolynomial.yz.y, reflectionTexture.sphericalPolynomial.yz.z);
  35137. this._activeEffect.setFloat3("vSphericalZX", reflectionTexture.sphericalPolynomial.zx.x, reflectionTexture.sphericalPolynomial.zx.y, reflectionTexture.sphericalPolynomial.zx.z);
  35138. }
  35139. }
  35140. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35141. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35142. this._uniformBuffer.updateMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  35143. }
  35144. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35145. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35146. this._uniformBuffer.updateMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  35147. }
  35148. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35149. if (this._metallicTexture) {
  35150. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  35151. this._uniformBuffer.updateMatrix("reflectivityMatrix", this._metallicTexture.getTextureMatrix());
  35152. }
  35153. else if (this._reflectivityTexture) {
  35154. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  35155. this._uniformBuffer.updateMatrix("reflectivityMatrix", this._reflectivityTexture.getTextureMatrix());
  35156. }
  35157. if (this._microSurfaceTexture) {
  35158. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  35159. this._uniformBuffer.updateMatrix("microSurfaceSamplerMatrix", this._microSurfaceTexture.getTextureMatrix());
  35160. }
  35161. }
  35162. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35163. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  35164. this._uniformBuffer.updateMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  35165. }
  35166. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35167. this._microsurfaceTextureLods.y = Math.round(Math.log(this._refractionTexture.getSize().width) * Math.LOG2E);
  35168. var depth = 1.0;
  35169. if (!this._refractionTexture.isCube) {
  35170. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  35171. if (this._refractionTexture.depth) {
  35172. depth = this._refractionTexture.depth;
  35173. }
  35174. }
  35175. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  35176. }
  35177. if ((reflectionTexture || this._refractionTexture)) {
  35178. this._uniformBuffer.updateFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  35179. }
  35180. }
  35181. // Point size
  35182. if (this.pointsCloud) {
  35183. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35184. }
  35185. // Colors
  35186. if (defines.METALLICWORKFLOW) {
  35187. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  35188. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  35189. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  35190. }
  35191. else {
  35192. // GAMMA CORRECTION.
  35193. this.convertColorToLinearSpaceToRef(this._reflectivityColor, BABYLON.PBRMaterial._scaledReflectivity);
  35194. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, this._microSurface);
  35195. }
  35196. // GAMMA CORRECTION.
  35197. this.convertColorToLinearSpaceToRef(this._emissiveColor, BABYLON.PBRMaterial._scaledEmissive);
  35198. this._uniformBuffer.updateColor3("vEmissiveColor", BABYLON.PBRMaterial._scaledEmissive);
  35199. // GAMMA CORRECTION.
  35200. this.convertColorToLinearSpaceToRef(this._reflectionColor, BABYLON.PBRMaterial._scaledReflection);
  35201. this._uniformBuffer.updateColor3("vReflectionColor", BABYLON.PBRMaterial._scaledReflection);
  35202. // GAMMA CORRECTION.
  35203. this.convertColorToLinearSpaceToRef(this._albedoColor, BABYLON.PBRMaterial._scaledAlbedo);
  35204. this._uniformBuffer.updateColor4("vAlbedoColor", BABYLON.PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  35205. // Misc
  35206. this._lightingInfos.x = this._directIntensity;
  35207. this._lightingInfos.y = this._emissiveIntensity;
  35208. this._lightingInfos.z = this._environmentIntensity;
  35209. this._lightingInfos.w = this._specularIntensity;
  35210. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  35211. }
  35212. // Textures
  35213. if (scene.texturesEnabled) {
  35214. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35215. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  35216. }
  35217. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35218. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  35219. }
  35220. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35221. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  35222. }
  35223. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35224. if (reflectionTexture.isCube) {
  35225. this._uniformBuffer.setTexture("reflectionCubeSampler", reflectionTexture);
  35226. }
  35227. else {
  35228. this._uniformBuffer.setTexture("reflection2DSampler", reflectionTexture);
  35229. }
  35230. }
  35231. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35232. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  35233. }
  35234. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35235. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  35236. }
  35237. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35238. if (this._metallicTexture) {
  35239. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  35240. }
  35241. else if (this._reflectivityTexture) {
  35242. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  35243. }
  35244. if (this._microSurfaceTexture) {
  35245. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  35246. }
  35247. }
  35248. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35249. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  35250. }
  35251. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35252. if (this._refractionTexture.isCube) {
  35253. this._uniformBuffer.setTexture("refractionCubeSampler", this._refractionTexture);
  35254. }
  35255. else {
  35256. this._uniformBuffer.setTexture("refraction2DSampler", this._refractionTexture);
  35257. }
  35258. }
  35259. if (this._cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  35260. BABYLON.ColorGradingTexture.Bind(this._cameraColorGradingTexture, this._activeEffect);
  35261. }
  35262. }
  35263. // Clip plane
  35264. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  35265. // Colors
  35266. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  35267. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  35268. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  35269. }
  35270. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  35271. // Lights
  35272. if (scene.lightsEnabled && !this._disableLighting) {
  35273. BABYLON.PBRMaterial.BindLights(scene, mesh, this._activeEffect, defines, this._useScalarInLinearSpace, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  35274. }
  35275. // View
  35276. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  35277. this.bindView(effect);
  35278. }
  35279. // Fog
  35280. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  35281. // Morph targets
  35282. if (defines.NUM_MORPH_INFLUENCERS) {
  35283. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  35284. }
  35285. this._cameraInfos.x = this._cameraExposure;
  35286. this._cameraInfos.y = this._cameraContrast;
  35287. effect.setVector4("vCameraInfos", this._cameraInfos);
  35288. if (this._cameraColorCurves) {
  35289. BABYLON.ColorCurves.Bind(this._cameraColorCurves, this._activeEffect);
  35290. }
  35291. // Log. depth
  35292. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  35293. }
  35294. this._uniformBuffer.update();
  35295. this._afterBind(mesh);
  35296. scene = null;
  35297. };
  35298. PBRBaseMaterial.prototype.getAnimatables = function () {
  35299. var results = [];
  35300. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  35301. results.push(this._albedoTexture);
  35302. }
  35303. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35304. results.push(this._ambientTexture);
  35305. }
  35306. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35307. results.push(this._opacityTexture);
  35308. }
  35309. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35310. results.push(this._reflectionTexture);
  35311. }
  35312. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35313. results.push(this._emissiveTexture);
  35314. }
  35315. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  35316. results.push(this._metallicTexture);
  35317. }
  35318. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  35319. results.push(this._reflectivityTexture);
  35320. }
  35321. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35322. results.push(this._bumpTexture);
  35323. }
  35324. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  35325. results.push(this._lightmapTexture);
  35326. }
  35327. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  35328. results.push(this._refractionTexture);
  35329. }
  35330. if (this._cameraColorGradingTexture && this._cameraColorGradingTexture.animations && this._cameraColorGradingTexture.animations.length > 0) {
  35331. results.push(this._cameraColorGradingTexture);
  35332. }
  35333. return results;
  35334. };
  35335. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35336. if (forceDisposeTextures) {
  35337. if (this._albedoTexture) {
  35338. this._albedoTexture.dispose();
  35339. }
  35340. if (this._ambientTexture) {
  35341. this._ambientTexture.dispose();
  35342. }
  35343. if (this._opacityTexture) {
  35344. this._opacityTexture.dispose();
  35345. }
  35346. if (this._reflectionTexture) {
  35347. this._reflectionTexture.dispose();
  35348. }
  35349. if (this._emissiveTexture) {
  35350. this._emissiveTexture.dispose();
  35351. }
  35352. if (this._metallicTexture) {
  35353. this._metallicTexture.dispose();
  35354. }
  35355. if (this._reflectivityTexture) {
  35356. this._reflectivityTexture.dispose();
  35357. }
  35358. if (this._bumpTexture) {
  35359. this._bumpTexture.dispose();
  35360. }
  35361. if (this._lightmapTexture) {
  35362. this._lightmapTexture.dispose();
  35363. }
  35364. if (this._refractionTexture) {
  35365. this._refractionTexture.dispose();
  35366. }
  35367. if (this._cameraColorGradingTexture) {
  35368. this._cameraColorGradingTexture.dispose();
  35369. }
  35370. }
  35371. this._renderTargets.dispose();
  35372. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  35373. };
  35374. return PBRBaseMaterial;
  35375. }(BABYLON.PushMaterial));
  35376. PBRBaseMaterial._scaledAlbedo = new BABYLON.Color3();
  35377. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  35378. PBRBaseMaterial._scaledEmissive = new BABYLON.Color3();
  35379. PBRBaseMaterial._scaledReflection = new BABYLON.Color3();
  35380. __decorate([
  35381. BABYLON.serialize()
  35382. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  35383. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  35384. })(BABYLON || (BABYLON = {}));
  35385. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  35386. var BABYLON;
  35387. (function (BABYLON) {
  35388. var Internals;
  35389. (function (Internals) {
  35390. /**
  35391. * The Physically based simple base material of BJS.
  35392. *
  35393. * This enables better naming and convention enforcements on top of the pbrMaterial.
  35394. * It is used as the base class for both the specGloss and metalRough conventions.
  35395. */
  35396. var PBRBaseSimpleMaterial = (function (_super) {
  35397. __extends(PBRBaseSimpleMaterial, _super);
  35398. /**
  35399. * Instantiates a new PBRMaterial instance.
  35400. *
  35401. * @param name The material name
  35402. * @param scene The scene the material will be use in.
  35403. */
  35404. function PBRBaseSimpleMaterial(name, scene) {
  35405. var _this = _super.call(this, name, scene) || this;
  35406. /**
  35407. * Number of Simultaneous lights allowed on the material.
  35408. */
  35409. _this.maxSimultaneousLights = 4;
  35410. /**
  35411. * If sets to true, disables all the lights affecting the material.
  35412. */
  35413. _this.disableLighting = false;
  35414. /**
  35415. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  35416. */
  35417. _this.invertNormalMapX = false;
  35418. /**
  35419. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  35420. */
  35421. _this.invertNormalMapY = false;
  35422. /**
  35423. * Emissivie color used to self-illuminate the model.
  35424. */
  35425. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  35426. /**
  35427. * Occlusion Channel Strenght.
  35428. */
  35429. _this.occlusionStrength = 1.0;
  35430. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35431. _this._useEmissiveAsIllumination = true;
  35432. _this._useAmbientInGrayScale = true;
  35433. _this._useScalarInLinearSpace = true;
  35434. return _this;
  35435. }
  35436. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  35437. /**
  35438. * Gets the current transparency mode.
  35439. */
  35440. get: function () {
  35441. return this._transparencyMode;
  35442. },
  35443. /**
  35444. * Sets the transparency mode of the material.
  35445. */
  35446. set: function (value) {
  35447. if (this._transparencyMode === value) {
  35448. return;
  35449. }
  35450. this._transparencyMode = value;
  35451. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  35452. this._forceAlphaTest = true;
  35453. }
  35454. else {
  35455. this._forceAlphaTest = false;
  35456. }
  35457. this._markAllSubMeshesAsTexturesDirty();
  35458. },
  35459. enumerable: true,
  35460. configurable: true
  35461. });
  35462. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  35463. /**
  35464. * Gets the current double sided mode.
  35465. */
  35466. get: function () {
  35467. return this._twoSidedLighting;
  35468. },
  35469. /**
  35470. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35471. */
  35472. set: function (value) {
  35473. if (this._twoSidedLighting === value) {
  35474. return;
  35475. }
  35476. this._twoSidedLighting = value;
  35477. this.backFaceCulling = !value;
  35478. this._markAllSubMeshesAsTexturesDirty();
  35479. },
  35480. enumerable: true,
  35481. configurable: true
  35482. });
  35483. /**
  35484. * Specifies wether or not the alpha value of the albedo texture should be used.
  35485. */
  35486. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  35487. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35488. };
  35489. /**
  35490. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  35491. */
  35492. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  35493. if (this._linkRefractionWithTransparency) {
  35494. return false;
  35495. }
  35496. return (this.alpha < 1.0) ||
  35497. (this._shouldUseAlphaFromAlbedoTexture() &&
  35498. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  35499. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  35500. };
  35501. /**
  35502. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  35503. */
  35504. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  35505. if (this._linkRefractionWithTransparency) {
  35506. return false;
  35507. }
  35508. return this._shouldUseAlphaFromAlbedoTexture() &&
  35509. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  35510. };
  35511. return PBRBaseSimpleMaterial;
  35512. }(BABYLON.PBRBaseMaterial));
  35513. __decorate([
  35514. BABYLON.serialize(),
  35515. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35516. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  35517. __decorate([
  35518. BABYLON.serialize(),
  35519. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35520. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  35521. __decorate([
  35522. BABYLON.serializeAsTexture(),
  35523. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  35524. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  35525. __decorate([
  35526. BABYLON.serialize(),
  35527. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35528. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  35529. __decorate([
  35530. BABYLON.serialize(),
  35531. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35532. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  35533. __decorate([
  35534. BABYLON.serializeAsTexture(),
  35535. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  35536. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  35537. __decorate([
  35538. BABYLON.serializeAsColor3("emissive"),
  35539. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35540. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  35541. __decorate([
  35542. BABYLON.serializeAsTexture(),
  35543. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35544. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  35545. __decorate([
  35546. BABYLON.serialize(),
  35547. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  35548. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  35549. __decorate([
  35550. BABYLON.serializeAsTexture(),
  35551. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  35552. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  35553. __decorate([
  35554. BABYLON.serialize(),
  35555. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  35556. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  35557. __decorate([
  35558. BABYLON.serialize()
  35559. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  35560. __decorate([
  35561. BABYLON.serialize()
  35562. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  35563. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  35564. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  35565. })(BABYLON || (BABYLON = {}));
  35566. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  35567. var BABYLON;
  35568. (function (BABYLON) {
  35569. /**
  35570. * The Physically based material of BJS.
  35571. *
  35572. * This offers the main features of a standard PBR material.
  35573. * For more information, please refer to the documentation :
  35574. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  35575. */
  35576. var PBRMaterial = (function (_super) {
  35577. __extends(PBRMaterial, _super);
  35578. /**
  35579. * Instantiates a new PBRMaterial instance.
  35580. *
  35581. * @param name The material name
  35582. * @param scene The scene the material will be use in.
  35583. */
  35584. function PBRMaterial(name, scene) {
  35585. var _this = _super.call(this, name, scene) || this;
  35586. /**
  35587. * Intensity of the direct lights e.g. the four lights available in your scene.
  35588. * This impacts both the direct diffuse and specular highlights.
  35589. */
  35590. _this.directIntensity = 1.0;
  35591. /**
  35592. * Intensity of the emissive part of the material.
  35593. * This helps controlling the emissive effect without modifying the emissive color.
  35594. */
  35595. _this.emissiveIntensity = 1.0;
  35596. /**
  35597. * Intensity of the environment e.g. how much the environment will light the object
  35598. * either through harmonics for rough material or through the refelction for shiny ones.
  35599. */
  35600. _this.environmentIntensity = 1.0;
  35601. /**
  35602. * This is a special control allowing the reduction of the specular highlights coming from the
  35603. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  35604. */
  35605. _this.specularIntensity = 1.0;
  35606. /**
  35607. * Debug Control allowing disabling the bump map on this material.
  35608. */
  35609. _this.disableBumpMap = false;
  35610. /**
  35611. * The camera exposure used on this material.
  35612. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  35613. * This corresponds to a photographic exposure.
  35614. */
  35615. _this.cameraExposure = 1.0;
  35616. /**
  35617. * The camera contrast used on this material.
  35618. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  35619. */
  35620. _this.cameraContrast = 1.0;
  35621. /**
  35622. * Color Grading 2D Lookup Texture.
  35623. * This allows special effects like sepia, black and white to sixties rendering style.
  35624. */
  35625. _this.cameraColorGradingTexture = null;
  35626. /**
  35627. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35628. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35629. * 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;
  35630. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35631. */
  35632. _this.cameraColorCurves = null;
  35633. /**
  35634. * AKA Occlusion Texture Intensity in other nomenclature.
  35635. */
  35636. _this.ambientTextureStrength = 1.0;
  35637. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  35638. /**
  35639. * AKA Diffuse Color in other nomenclature.
  35640. */
  35641. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  35642. /**
  35643. * AKA Specular Color in other nomenclature.
  35644. */
  35645. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  35646. _this.reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  35647. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  35648. /**
  35649. * AKA Glossiness in other nomenclature.
  35650. */
  35651. _this.microSurface = 0.9;
  35652. /**
  35653. * source material index of refraction (IOR)' / 'destination material IOR.
  35654. */
  35655. _this.indexOfRefraction = 0.66;
  35656. /**
  35657. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  35658. */
  35659. _this.invertRefractionY = false;
  35660. /**
  35661. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  35662. * Materials half opaque for instance using refraction could benefit from this control.
  35663. */
  35664. _this.linkRefractionWithTransparency = false;
  35665. _this.useLightmapAsShadowmap = false;
  35666. /**
  35667. * In this mode, the emissive informtaion will always be added to the lighting once.
  35668. * A light for instance can be thought as emissive.
  35669. */
  35670. _this.useEmissiveAsIllumination = false;
  35671. /**
  35672. * Secifies that the alpha is coming form the albedo channel alpha channel.
  35673. */
  35674. _this.useAlphaFromAlbedoTexture = false;
  35675. /**
  35676. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  35677. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  35678. */
  35679. _this.useSpecularOverAlpha = true;
  35680. /**
  35681. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  35682. */
  35683. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  35684. /**
  35685. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  35686. */
  35687. _this.useRoughnessFromMetallicTextureAlpha = true;
  35688. /**
  35689. * Specifies if the metallic texture contains the roughness information in its green channel.
  35690. */
  35691. _this.useRoughnessFromMetallicTextureGreen = false;
  35692. /**
  35693. * Specifies if the metallic texture contains the metallness information in its blue channel.
  35694. */
  35695. _this.useMetallnessFromMetallicTextureBlue = false;
  35696. /**
  35697. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  35698. */
  35699. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  35700. /**
  35701. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  35702. */
  35703. _this.useAmbientInGrayScale = false;
  35704. /**
  35705. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  35706. * The material will try to infer what glossiness each pixel should be.
  35707. */
  35708. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  35709. /**
  35710. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  35711. * the creation of the material.
  35712. */
  35713. _this.useScalarInLinearSpace = false;
  35714. /**
  35715. * BJS is using an harcoded light falloff based on a manually sets up range.
  35716. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  35717. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  35718. */
  35719. _this.usePhysicalLightFalloff = true;
  35720. /**
  35721. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  35722. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  35723. */
  35724. _this.useRadianceOverAlpha = true;
  35725. /**
  35726. * Allows using the bump map in parallax mode.
  35727. */
  35728. _this.useParallax = false;
  35729. /**
  35730. * Allows using the bump map in parallax occlusion mode.
  35731. */
  35732. _this.useParallaxOcclusion = false;
  35733. /**
  35734. * Controls the scale bias of the parallax mode.
  35735. */
  35736. _this.parallaxScaleBias = 0.05;
  35737. /**
  35738. * If sets to true, disables all the lights affecting the material.
  35739. */
  35740. _this.disableLighting = false;
  35741. /**
  35742. * Number of Simultaneous lights allowed on the material.
  35743. */
  35744. _this.maxSimultaneousLights = 4;
  35745. /**
  35746. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  35747. */
  35748. _this.invertNormalMapX = false;
  35749. /**
  35750. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  35751. */
  35752. _this.invertNormalMapY = false;
  35753. /**
  35754. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35755. */
  35756. _this.twoSidedLighting = false;
  35757. return _this;
  35758. }
  35759. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  35760. /**
  35761. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  35762. */
  35763. get: function () {
  35764. return this._PBRMATERIAL_OPAQUE;
  35765. },
  35766. enumerable: true,
  35767. configurable: true
  35768. });
  35769. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  35770. /**
  35771. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  35772. */
  35773. get: function () {
  35774. return this._PBRMATERIAL_ALPHATEST;
  35775. },
  35776. enumerable: true,
  35777. configurable: true
  35778. });
  35779. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  35780. /**
  35781. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  35782. */
  35783. get: function () {
  35784. return this._PBRMATERIAL_ALPHABLEND;
  35785. },
  35786. enumerable: true,
  35787. configurable: true
  35788. });
  35789. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  35790. /**
  35791. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  35792. * They are also discarded below the alpha cutoff threshold to improve performances.
  35793. */
  35794. get: function () {
  35795. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  35796. },
  35797. enumerable: true,
  35798. configurable: true
  35799. });
  35800. PBRMaterial.prototype.getClassName = function () {
  35801. return "PBRMaterial";
  35802. };
  35803. PBRMaterial.prototype.clone = function (name) {
  35804. var _this = this;
  35805. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  35806. };
  35807. PBRMaterial.prototype.serialize = function () {
  35808. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  35809. serializationObject.customType = "BABYLON.PBRMaterial";
  35810. return serializationObject;
  35811. };
  35812. // Statics
  35813. PBRMaterial.Parse = function (source, scene, rootUrl) {
  35814. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  35815. };
  35816. return PBRMaterial;
  35817. }(BABYLON.PBRBaseMaterial));
  35818. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  35819. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  35820. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  35821. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  35822. __decorate([
  35823. BABYLON.serialize(),
  35824. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35825. ], PBRMaterial.prototype, "directIntensity", void 0);
  35826. __decorate([
  35827. BABYLON.serialize(),
  35828. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35829. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  35830. __decorate([
  35831. BABYLON.serialize(),
  35832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35833. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  35834. __decorate([
  35835. BABYLON.serialize(),
  35836. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35837. ], PBRMaterial.prototype, "specularIntensity", void 0);
  35838. __decorate([
  35839. BABYLON.serialize(),
  35840. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35841. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  35842. __decorate([
  35843. BABYLON.serialize(),
  35844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35845. ], PBRMaterial.prototype, "cameraExposure", void 0);
  35846. __decorate([
  35847. BABYLON.serialize(),
  35848. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35849. ], PBRMaterial.prototype, "cameraContrast", void 0);
  35850. __decorate([
  35851. BABYLON.serializeAsTexture(),
  35852. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35853. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  35854. __decorate([
  35855. BABYLON.serializeAsColorCurves(),
  35856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35857. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  35858. __decorate([
  35859. BABYLON.serializeAsTexture(),
  35860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35861. ], PBRMaterial.prototype, "albedoTexture", void 0);
  35862. __decorate([
  35863. BABYLON.serializeAsTexture(),
  35864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35865. ], PBRMaterial.prototype, "ambientTexture", void 0);
  35866. __decorate([
  35867. BABYLON.serialize(),
  35868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35869. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  35870. __decorate([
  35871. BABYLON.serializeAsTexture(),
  35872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35873. ], PBRMaterial.prototype, "opacityTexture", void 0);
  35874. __decorate([
  35875. BABYLON.serializeAsTexture(),
  35876. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35877. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  35878. __decorate([
  35879. BABYLON.serializeAsTexture(),
  35880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35881. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  35882. __decorate([
  35883. BABYLON.serializeAsTexture(),
  35884. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35885. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  35886. __decorate([
  35887. BABYLON.serializeAsTexture(),
  35888. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35889. ], PBRMaterial.prototype, "metallicTexture", void 0);
  35890. __decorate([
  35891. BABYLON.serialize(),
  35892. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35893. ], PBRMaterial.prototype, "metallic", void 0);
  35894. __decorate([
  35895. BABYLON.serialize(),
  35896. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35897. ], PBRMaterial.prototype, "roughness", void 0);
  35898. __decorate([
  35899. BABYLON.serializeAsTexture(),
  35900. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35901. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  35902. __decorate([
  35903. BABYLON.serializeAsTexture(),
  35904. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35905. ], PBRMaterial.prototype, "bumpTexture", void 0);
  35906. __decorate([
  35907. BABYLON.serializeAsTexture(),
  35908. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  35909. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  35910. __decorate([
  35911. BABYLON.serializeAsTexture(),
  35912. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35913. ], PBRMaterial.prototype, "refractionTexture", void 0);
  35914. __decorate([
  35915. BABYLON.serializeAsColor3("ambient"),
  35916. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35917. ], PBRMaterial.prototype, "ambientColor", void 0);
  35918. __decorate([
  35919. BABYLON.serializeAsColor3("albedo"),
  35920. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35921. ], PBRMaterial.prototype, "albedoColor", void 0);
  35922. __decorate([
  35923. BABYLON.serializeAsColor3("reflectivity"),
  35924. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35925. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  35926. __decorate([
  35927. BABYLON.serializeAsColor3("reflection"),
  35928. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35929. ], PBRMaterial.prototype, "reflectionColor", void 0);
  35930. __decorate([
  35931. BABYLON.serializeAsColor3("emissive"),
  35932. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35933. ], PBRMaterial.prototype, "emissiveColor", void 0);
  35934. __decorate([
  35935. BABYLON.serialize(),
  35936. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35937. ], PBRMaterial.prototype, "microSurface", void 0);
  35938. __decorate([
  35939. BABYLON.serialize(),
  35940. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35941. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  35942. __decorate([
  35943. BABYLON.serialize(),
  35944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35945. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  35946. __decorate([
  35947. BABYLON.serializeAsFresnelParameters(),
  35948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35949. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  35950. __decorate([
  35951. BABYLON.serializeAsFresnelParameters(),
  35952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35953. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  35954. __decorate([
  35955. BABYLON.serialize(),
  35956. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35957. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  35958. __decorate([
  35959. BABYLON.serialize(),
  35960. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35961. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  35962. __decorate([
  35963. BABYLON.serialize(),
  35964. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35965. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  35966. __decorate([
  35967. BABYLON.serialize(),
  35968. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35969. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  35970. __decorate([
  35971. BABYLON.serialize(),
  35972. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35973. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  35974. __decorate([
  35975. BABYLON.serialize(),
  35976. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35977. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  35978. __decorate([
  35979. BABYLON.serialize(),
  35980. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35981. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  35982. __decorate([
  35983. BABYLON.serialize(),
  35984. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35985. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  35986. __decorate([
  35987. BABYLON.serialize(),
  35988. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35989. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  35990. __decorate([
  35991. BABYLON.serialize(),
  35992. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35993. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  35994. __decorate([
  35995. BABYLON.serialize(),
  35996. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35997. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  35998. __decorate([
  35999. BABYLON.serialize(),
  36000. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36001. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  36002. __decorate([
  36003. BABYLON.serialize(),
  36004. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36005. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  36006. __decorate([
  36007. BABYLON.serialize(),
  36008. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36009. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  36010. __decorate([
  36011. BABYLON.serialize(),
  36012. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36013. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  36014. __decorate([
  36015. BABYLON.serialize(),
  36016. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36017. ], PBRMaterial.prototype, "useParallax", void 0);
  36018. __decorate([
  36019. BABYLON.serialize(),
  36020. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36021. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  36022. __decorate([
  36023. BABYLON.serialize(),
  36024. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36025. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  36026. __decorate([
  36027. BABYLON.serialize(),
  36028. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36029. ], PBRMaterial.prototype, "disableLighting", void 0);
  36030. __decorate([
  36031. BABYLON.serialize(),
  36032. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36033. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  36034. __decorate([
  36035. BABYLON.serialize(),
  36036. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36037. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  36038. __decorate([
  36039. BABYLON.serialize(),
  36040. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36041. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  36042. __decorate([
  36043. BABYLON.serialize(),
  36044. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36045. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  36046. BABYLON.PBRMaterial = PBRMaterial;
  36047. })(BABYLON || (BABYLON = {}));
  36048. //# sourceMappingURL=babylon.pbrMaterial.js.map
  36049. var BABYLON;
  36050. (function (BABYLON) {
  36051. /**
  36052. * The PBR material of BJS following the metal roughness convention.
  36053. *
  36054. * This fits to the define PBR convention in the GLTF definition:
  36055. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  36056. */
  36057. var PBRMetallicRoughnessMaterial = (function (_super) {
  36058. __extends(PBRMetallicRoughnessMaterial, _super);
  36059. /**
  36060. * Instantiates a new PBRMetalRoughnessMaterial instance.
  36061. *
  36062. * @param name The material name
  36063. * @param scene The scene the material will be use in.
  36064. */
  36065. function PBRMetallicRoughnessMaterial(name, scene) {
  36066. var _this = _super.call(this, name, scene) || this;
  36067. _this._useRoughnessFromMetallicTextureGreen = true;
  36068. _this._useMetallnessFromMetallicTextureBlue = true;
  36069. return _this;
  36070. }
  36071. /**
  36072. * Return the currrent class name of the material.
  36073. */
  36074. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  36075. return "PBRMetallicRoughnessMaterial";
  36076. };
  36077. /**
  36078. * Serialize the material to a parsable JSON object.
  36079. */
  36080. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  36081. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36082. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  36083. return serializationObject;
  36084. };
  36085. /**
  36086. * Parses a JSON object correponding to the serialize function.
  36087. */
  36088. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  36089. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  36090. };
  36091. return PBRMetallicRoughnessMaterial;
  36092. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  36093. __decorate([
  36094. BABYLON.serializeAsTexture(),
  36095. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  36096. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  36097. __decorate([
  36098. BABYLON.serializeAsTexture(),
  36099. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  36100. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  36101. __decorate([
  36102. BABYLON.serialize(),
  36103. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36104. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  36105. __decorate([
  36106. BABYLON.serialize(),
  36107. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36108. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  36109. __decorate([
  36110. BABYLON.serializeAsTexture(),
  36111. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  36112. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  36113. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  36114. })(BABYLON || (BABYLON = {}));
  36115. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  36116. var BABYLON;
  36117. (function (BABYLON) {
  36118. /**
  36119. * The PBR material of BJS following the specular glossiness convention.
  36120. *
  36121. * This fits to the define PBR convention in the GLTF definition:
  36122. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  36123. */
  36124. var PBRSpecularGlossinessMaterial = (function (_super) {
  36125. __extends(PBRSpecularGlossinessMaterial, _super);
  36126. /**
  36127. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  36128. *
  36129. * @param name The material name
  36130. * @param scene The scene the material will be use in.
  36131. */
  36132. function PBRSpecularGlossinessMaterial(name, scene) {
  36133. var _this = _super.call(this, name, scene) || this;
  36134. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  36135. return _this;
  36136. }
  36137. /**
  36138. * Return the currrent class name of the material.
  36139. */
  36140. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  36141. return "PBRSpecularGlossinessMaterial";
  36142. };
  36143. /**
  36144. * Serialize the material to a parsable JSON object.
  36145. */
  36146. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  36147. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36148. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  36149. return serializationObject;
  36150. };
  36151. /**
  36152. * Parses a JSON object correponding to the serialize function.
  36153. */
  36154. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  36155. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  36156. };
  36157. return PBRSpecularGlossinessMaterial;
  36158. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  36159. __decorate([
  36160. BABYLON.serializeAsColor3(),
  36161. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  36162. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  36163. __decorate([
  36164. BABYLON.serializeAsTexture(),
  36165. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  36166. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  36167. __decorate([
  36168. BABYLON.serializeAsColor3(),
  36169. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  36170. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  36171. __decorate([
  36172. BABYLON.serialize(),
  36173. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  36174. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  36175. __decorate([
  36176. BABYLON.serializeAsTexture(),
  36177. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  36178. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  36179. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  36180. })(BABYLON || (BABYLON = {}));
  36181. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  36182. var BABYLON;
  36183. (function (BABYLON) {
  36184. var ShaderMaterial = (function (_super) {
  36185. __extends(ShaderMaterial, _super);
  36186. function ShaderMaterial(name, scene, shaderPath, options) {
  36187. var _this = _super.call(this, name, scene) || this;
  36188. _this._textures = {};
  36189. _this._textureArrays = {};
  36190. _this._floats = {};
  36191. _this._floatsArrays = {};
  36192. _this._colors3 = {};
  36193. _this._colors4 = {};
  36194. _this._vectors2 = {};
  36195. _this._vectors3 = {};
  36196. _this._vectors4 = {};
  36197. _this._matrices = {};
  36198. _this._matrices3x3 = {};
  36199. _this._matrices2x2 = {};
  36200. _this._vectors3Arrays = {};
  36201. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  36202. _this._shaderPath = shaderPath;
  36203. options.needAlphaBlending = options.needAlphaBlending || false;
  36204. options.needAlphaTesting = options.needAlphaTesting || false;
  36205. options.attributes = options.attributes || ["position", "normal", "uv"];
  36206. options.uniforms = options.uniforms || ["worldViewProjection"];
  36207. options.uniformBuffers = options.uniformBuffers || [];
  36208. options.samplers = options.samplers || [];
  36209. options.defines = options.defines || [];
  36210. _this._options = options;
  36211. return _this;
  36212. }
  36213. ShaderMaterial.prototype.getClassName = function () {
  36214. return "ShaderMaterial";
  36215. };
  36216. ShaderMaterial.prototype.needAlphaBlending = function () {
  36217. return this._options.needAlphaBlending;
  36218. };
  36219. ShaderMaterial.prototype.needAlphaTesting = function () {
  36220. return this._options.needAlphaTesting;
  36221. };
  36222. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  36223. if (this._options.uniforms.indexOf(uniformName) === -1) {
  36224. this._options.uniforms.push(uniformName);
  36225. }
  36226. };
  36227. ShaderMaterial.prototype.setTexture = function (name, texture) {
  36228. if (this._options.samplers.indexOf(name) === -1) {
  36229. this._options.samplers.push(name);
  36230. }
  36231. this._textures[name] = texture;
  36232. return this;
  36233. };
  36234. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  36235. if (this._options.samplers.indexOf(name) === -1) {
  36236. this._options.samplers.push(name);
  36237. }
  36238. this._checkUniform(name);
  36239. this._textureArrays[name] = textures;
  36240. return this;
  36241. };
  36242. ShaderMaterial.prototype.setFloat = function (name, value) {
  36243. this._checkUniform(name);
  36244. this._floats[name] = value;
  36245. return this;
  36246. };
  36247. ShaderMaterial.prototype.setFloats = function (name, value) {
  36248. this._checkUniform(name);
  36249. this._floatsArrays[name] = value;
  36250. return this;
  36251. };
  36252. ShaderMaterial.prototype.setColor3 = function (name, value) {
  36253. this._checkUniform(name);
  36254. this._colors3[name] = value;
  36255. return this;
  36256. };
  36257. ShaderMaterial.prototype.setColor4 = function (name, value) {
  36258. this._checkUniform(name);
  36259. this._colors4[name] = value;
  36260. return this;
  36261. };
  36262. ShaderMaterial.prototype.setVector2 = function (name, value) {
  36263. this._checkUniform(name);
  36264. this._vectors2[name] = value;
  36265. return this;
  36266. };
  36267. ShaderMaterial.prototype.setVector3 = function (name, value) {
  36268. this._checkUniform(name);
  36269. this._vectors3[name] = value;
  36270. return this;
  36271. };
  36272. ShaderMaterial.prototype.setVector4 = function (name, value) {
  36273. this._checkUniform(name);
  36274. this._vectors4[name] = value;
  36275. return this;
  36276. };
  36277. ShaderMaterial.prototype.setMatrix = function (name, value) {
  36278. this._checkUniform(name);
  36279. this._matrices[name] = value;
  36280. return this;
  36281. };
  36282. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  36283. this._checkUniform(name);
  36284. this._matrices3x3[name] = value;
  36285. return this;
  36286. };
  36287. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  36288. this._checkUniform(name);
  36289. this._matrices2x2[name] = value;
  36290. return this;
  36291. };
  36292. ShaderMaterial.prototype.setArray3 = function (name, value) {
  36293. this._checkUniform(name);
  36294. this._vectors3Arrays[name] = value;
  36295. return this;
  36296. };
  36297. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  36298. if (!mesh) {
  36299. return true;
  36300. }
  36301. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  36302. return false;
  36303. }
  36304. return false;
  36305. };
  36306. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  36307. var scene = this.getScene();
  36308. var engine = scene.getEngine();
  36309. if (!this.checkReadyOnEveryCall) {
  36310. if (this._renderId === scene.getRenderId()) {
  36311. if (this._checkCache(scene, mesh, useInstances)) {
  36312. return true;
  36313. }
  36314. }
  36315. }
  36316. // Instances
  36317. var defines = [];
  36318. var attribs = [];
  36319. var fallbacks = new BABYLON.EffectFallbacks();
  36320. if (useInstances) {
  36321. defines.push("#define INSTANCES");
  36322. }
  36323. for (var index = 0; index < this._options.defines.length; index++) {
  36324. defines.push(this._options.defines[index]);
  36325. }
  36326. for (var index = 0; index < this._options.attributes.length; index++) {
  36327. attribs.push(this._options.attributes[index]);
  36328. }
  36329. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36330. attribs.push(BABYLON.VertexBuffer.ColorKind);
  36331. defines.push("#define VERTEXCOLOR");
  36332. }
  36333. // Bones
  36334. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  36335. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36336. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36337. if (mesh.numBoneInfluencers > 4) {
  36338. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36339. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  36340. }
  36341. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  36342. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  36343. fallbacks.addCPUSkinningFallback(0, mesh);
  36344. }
  36345. else {
  36346. defines.push("#define NUM_BONE_INFLUENCERS 0");
  36347. }
  36348. // Textures
  36349. for (var name in this._textures) {
  36350. if (!this._textures[name].isReady()) {
  36351. return false;
  36352. }
  36353. }
  36354. // Alpha test
  36355. if (engine.getAlphaTesting()) {
  36356. defines.push("#define ALPHATEST");
  36357. }
  36358. var previousEffect = this._effect;
  36359. var join = defines.join("\n");
  36360. this._effect = engine.createEffect(this._shaderPath, {
  36361. attributes: attribs,
  36362. uniformsNames: this._options.uniforms,
  36363. uniformBuffersNames: this._options.uniformBuffers,
  36364. samplers: this._options.samplers,
  36365. defines: join,
  36366. fallbacks: fallbacks,
  36367. onCompiled: this.onCompiled,
  36368. onError: this.onError
  36369. }, engine);
  36370. if (!this._effect.isReady()) {
  36371. return false;
  36372. }
  36373. if (previousEffect !== this._effect) {
  36374. scene.resetCachedMaterial();
  36375. }
  36376. this._renderId = scene.getRenderId();
  36377. return true;
  36378. };
  36379. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  36380. var scene = this.getScene();
  36381. if (this._options.uniforms.indexOf("world") !== -1) {
  36382. this._effect.setMatrix("world", world);
  36383. }
  36384. if (this._options.uniforms.indexOf("worldView") !== -1) {
  36385. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  36386. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  36387. }
  36388. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  36389. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  36390. }
  36391. };
  36392. ShaderMaterial.prototype.bind = function (world, mesh) {
  36393. // Std values
  36394. this.bindOnlyWorldMatrix(world);
  36395. if (this.getScene().getCachedMaterial() !== this) {
  36396. if (this._options.uniforms.indexOf("view") !== -1) {
  36397. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  36398. }
  36399. if (this._options.uniforms.indexOf("projection") !== -1) {
  36400. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  36401. }
  36402. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  36403. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  36404. }
  36405. // Bones
  36406. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  36407. var name;
  36408. // Texture
  36409. for (name in this._textures) {
  36410. this._effect.setTexture(name, this._textures[name]);
  36411. }
  36412. // Texture arrays
  36413. for (name in this._textureArrays) {
  36414. this._effect.setTextureArray(name, this._textureArrays[name]);
  36415. }
  36416. // Float
  36417. for (name in this._floats) {
  36418. this._effect.setFloat(name, this._floats[name]);
  36419. }
  36420. // Float s
  36421. for (name in this._floatsArrays) {
  36422. this._effect.setArray(name, this._floatsArrays[name]);
  36423. }
  36424. // Color3
  36425. for (name in this._colors3) {
  36426. this._effect.setColor3(name, this._colors3[name]);
  36427. }
  36428. // Color4
  36429. for (name in this._colors4) {
  36430. var color = this._colors4[name];
  36431. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  36432. }
  36433. // Vector2
  36434. for (name in this._vectors2) {
  36435. this._effect.setVector2(name, this._vectors2[name]);
  36436. }
  36437. // Vector3
  36438. for (name in this._vectors3) {
  36439. this._effect.setVector3(name, this._vectors3[name]);
  36440. }
  36441. // Vector4
  36442. for (name in this._vectors4) {
  36443. this._effect.setVector4(name, this._vectors4[name]);
  36444. }
  36445. // Matrix
  36446. for (name in this._matrices) {
  36447. this._effect.setMatrix(name, this._matrices[name]);
  36448. }
  36449. // Matrix 3x3
  36450. for (name in this._matrices3x3) {
  36451. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  36452. }
  36453. // Matrix 2x2
  36454. for (name in this._matrices2x2) {
  36455. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  36456. }
  36457. // Vector3Array
  36458. for (name in this._vectors3Arrays) {
  36459. this._effect.setArray3(name, this._vectors3Arrays[name]);
  36460. }
  36461. }
  36462. this._afterBind(mesh);
  36463. };
  36464. ShaderMaterial.prototype.clone = function (name) {
  36465. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  36466. return newShaderMaterial;
  36467. };
  36468. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36469. if (forceDisposeTextures) {
  36470. var name;
  36471. for (name in this._textures) {
  36472. this._textures[name].dispose();
  36473. }
  36474. for (name in this._textureArrays) {
  36475. var array = this._textureArrays[name];
  36476. for (var index = 0; index < array.length; index++) {
  36477. array[index].dispose();
  36478. }
  36479. }
  36480. }
  36481. this._textures = {};
  36482. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  36483. };
  36484. ShaderMaterial.prototype.serialize = function () {
  36485. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36486. serializationObject.customType = "BABYLON.ShaderMaterial";
  36487. serializationObject.options = this._options;
  36488. serializationObject.shaderPath = this._shaderPath;
  36489. var name;
  36490. // Texture
  36491. serializationObject.textures = {};
  36492. for (name in this._textures) {
  36493. serializationObject.textures[name] = this._textures[name].serialize();
  36494. }
  36495. // Texture arrays
  36496. serializationObject.textureArrays = {};
  36497. for (name in this._textureArrays) {
  36498. serializationObject.textureArrays[name] = [];
  36499. var array = this._textureArrays[name];
  36500. for (var index = 0; index < array.length; index++) {
  36501. serializationObject.textureArrays[name].push(array[index].serialize());
  36502. }
  36503. }
  36504. // Float
  36505. serializationObject.floats = {};
  36506. for (name in this._floats) {
  36507. serializationObject.floats[name] = this._floats[name];
  36508. }
  36509. // Float s
  36510. serializationObject.floatArrays = {};
  36511. for (name in this._floatsArrays) {
  36512. serializationObject.floatArrays[name] = this._floatsArrays[name];
  36513. }
  36514. // Color3
  36515. serializationObject.colors3 = {};
  36516. for (name in this._colors3) {
  36517. serializationObject.colors3[name] = this._colors3[name].asArray();
  36518. }
  36519. // Color4
  36520. serializationObject.colors4 = {};
  36521. for (name in this._colors4) {
  36522. serializationObject.colors4[name] = this._colors4[name].asArray();
  36523. }
  36524. // Vector2
  36525. serializationObject.vectors2 = {};
  36526. for (name in this._vectors2) {
  36527. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  36528. }
  36529. // Vector3
  36530. serializationObject.vectors3 = {};
  36531. for (name in this._vectors3) {
  36532. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  36533. }
  36534. // Vector4
  36535. serializationObject.vectors4 = {};
  36536. for (name in this._vectors4) {
  36537. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  36538. }
  36539. // Matrix
  36540. serializationObject.matrices = {};
  36541. for (name in this._matrices) {
  36542. serializationObject.matrices[name] = this._matrices[name].asArray();
  36543. }
  36544. // Matrix 3x3
  36545. serializationObject.matrices3x3 = {};
  36546. for (name in this._matrices3x3) {
  36547. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  36548. }
  36549. // Matrix 2x2
  36550. serializationObject.matrices2x2 = {};
  36551. for (name in this._matrices2x2) {
  36552. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  36553. }
  36554. // Vector3Array
  36555. serializationObject.vectors3Arrays = {};
  36556. for (name in this._vectors3Arrays) {
  36557. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  36558. }
  36559. return serializationObject;
  36560. };
  36561. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  36562. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  36563. var name;
  36564. // Texture
  36565. for (name in source.textures) {
  36566. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  36567. }
  36568. // Texture arrays
  36569. for (name in source.textureArrays) {
  36570. var array = source.textureArrays[name];
  36571. var textureArray = new Array();
  36572. for (var index = 0; index < array.length; index++) {
  36573. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  36574. }
  36575. material.setTextureArray(name, textureArray);
  36576. }
  36577. // Float
  36578. for (name in source.floats) {
  36579. material.setFloat(name, source.floats[name]);
  36580. }
  36581. // Float s
  36582. for (name in source.floatsArrays) {
  36583. material.setFloats(name, source.floatsArrays[name]);
  36584. }
  36585. // Color3
  36586. for (name in source.colors3) {
  36587. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  36588. }
  36589. // Color4
  36590. for (name in source.colors4) {
  36591. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  36592. }
  36593. // Vector2
  36594. for (name in source.vectors2) {
  36595. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  36596. }
  36597. // Vector3
  36598. for (name in source.vectors3) {
  36599. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  36600. }
  36601. // Vector4
  36602. for (name in source.vectors4) {
  36603. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  36604. }
  36605. // Matrix
  36606. for (name in source.matrices) {
  36607. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  36608. }
  36609. // Matrix 3x3
  36610. for (name in source.matrices3x3) {
  36611. material.setMatrix3x3(name, source.matrices3x3[name]);
  36612. }
  36613. // Matrix 2x2
  36614. for (name in source.matrices2x2) {
  36615. material.setMatrix2x2(name, source.matrices2x2[name]);
  36616. }
  36617. // Vector3Array
  36618. for (name in source.vectors3Arrays) {
  36619. material.setArray3(name, source.vectors3Arrays[name]);
  36620. }
  36621. return material;
  36622. };
  36623. return ShaderMaterial;
  36624. }(BABYLON.Material));
  36625. BABYLON.ShaderMaterial = ShaderMaterial;
  36626. })(BABYLON || (BABYLON = {}));
  36627. //# sourceMappingURL=babylon.shaderMaterial.js.map
  36628. var BABYLON;
  36629. (function (BABYLON) {
  36630. var MeshBuilder = (function () {
  36631. function MeshBuilder() {
  36632. }
  36633. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  36634. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  36635. return BABYLON.Mesh.DOUBLESIDE;
  36636. }
  36637. if (orientation === undefined || orientation === null) {
  36638. return BABYLON.Mesh.FRONTSIDE;
  36639. }
  36640. return orientation;
  36641. };
  36642. /**
  36643. * Creates a box mesh.
  36644. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  36645. * The parameter `size` sets the size (float) of each box side (default 1).
  36646. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  36647. * 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).
  36648. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  36649. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36650. * 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).
  36651. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  36652. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  36653. */
  36654. MeshBuilder.CreateBox = function (name, options, scene) {
  36655. var box = new BABYLON.Mesh(name, scene);
  36656. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  36657. box.sideOrientation = options.sideOrientation;
  36658. var vertexData = BABYLON.VertexData.CreateBox(options);
  36659. vertexData.applyToMesh(box, options.updatable);
  36660. return box;
  36661. };
  36662. /**
  36663. * Creates a sphere mesh.
  36664. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  36665. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  36666. * 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`).
  36667. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  36668. * 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
  36669. * 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).
  36670. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36671. * 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).
  36672. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  36673. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  36674. */
  36675. MeshBuilder.CreateSphere = function (name, options, scene) {
  36676. var sphere = new BABYLON.Mesh(name, scene);
  36677. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  36678. sphere.sideOrientation = options.sideOrientation;
  36679. var vertexData = BABYLON.VertexData.CreateSphere(options);
  36680. vertexData.applyToMesh(sphere, options.updatable);
  36681. return sphere;
  36682. };
  36683. /**
  36684. * Creates a plane polygonal mesh. By default, this is a disc.
  36685. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  36686. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  36687. * 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.
  36688. * 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
  36689. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36690. * 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).
  36691. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  36692. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  36693. */
  36694. MeshBuilder.CreateDisc = function (name, options, scene) {
  36695. var disc = new BABYLON.Mesh(name, scene);
  36696. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  36697. disc.sideOrientation = options.sideOrientation;
  36698. var vertexData = BABYLON.VertexData.CreateDisc(options);
  36699. vertexData.applyToMesh(disc, options.updatable);
  36700. return disc;
  36701. };
  36702. /**
  36703. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  36704. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  36705. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  36706. * 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`).
  36707. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  36708. * 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.
  36709. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36710. * 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).
  36711. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  36712. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  36713. */
  36714. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  36715. var sphere = new BABYLON.Mesh(name, scene);
  36716. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  36717. sphere.sideOrientation = options.sideOrientation;
  36718. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  36719. vertexData.applyToMesh(sphere, options.updatable);
  36720. return sphere;
  36721. };
  36722. ;
  36723. /**
  36724. * Creates a ribbon mesh.
  36725. * 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.
  36726. *
  36727. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  36728. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  36729. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  36730. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  36731. * 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.
  36732. * 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.
  36733. * 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
  36734. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36735. * 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).
  36736. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  36737. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  36738. * 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.
  36739. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  36740. * 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
  36741. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  36742. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  36743. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  36744. */
  36745. MeshBuilder.CreateRibbon = function (name, options, scene) {
  36746. var pathArray = options.pathArray;
  36747. var closeArray = options.closeArray;
  36748. var closePath = options.closePath;
  36749. var offset = options.offset;
  36750. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  36751. var instance = options.instance;
  36752. var updatable = options.updatable;
  36753. if (instance) {
  36754. // positionFunction : ribbon case
  36755. // only pathArray and sideOrientation parameters are taken into account for positions update
  36756. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  36757. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  36758. var positionFunction = function (positions) {
  36759. var minlg = pathArray[0].length;
  36760. var i = 0;
  36761. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  36762. for (var si = 1; si <= ns; si++) {
  36763. for (var p = 0; p < pathArray.length; p++) {
  36764. var path = pathArray[p];
  36765. var l = path.length;
  36766. minlg = (minlg < l) ? minlg : l;
  36767. var j = 0;
  36768. while (j < minlg) {
  36769. positions[i] = path[j].x;
  36770. positions[i + 1] = path[j].y;
  36771. positions[i + 2] = path[j].z;
  36772. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  36773. BABYLON.Tmp.Vector3[0].x = path[j].x;
  36774. }
  36775. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  36776. BABYLON.Tmp.Vector3[1].x = path[j].x;
  36777. }
  36778. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  36779. BABYLON.Tmp.Vector3[0].y = path[j].y;
  36780. }
  36781. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  36782. BABYLON.Tmp.Vector3[1].y = path[j].y;
  36783. }
  36784. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  36785. BABYLON.Tmp.Vector3[0].z = path[j].z;
  36786. }
  36787. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  36788. BABYLON.Tmp.Vector3[1].z = path[j].z;
  36789. }
  36790. j++;
  36791. i += 3;
  36792. }
  36793. if (instance._closePath) {
  36794. positions[i] = path[0].x;
  36795. positions[i + 1] = path[0].y;
  36796. positions[i + 2] = path[0].z;
  36797. i += 3;
  36798. }
  36799. }
  36800. }
  36801. };
  36802. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36803. positionFunction(positions);
  36804. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  36805. instance._boundingInfo.update(instance._worldMatrix);
  36806. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  36807. if (options.colors) {
  36808. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36809. for (var c = 0; c < options.colors.length; c++) {
  36810. colors[c * 4] = options.colors[c].r;
  36811. colors[c * 4 + 1] = options.colors[c].g;
  36812. colors[c * 4 + 2] = options.colors[c].b;
  36813. colors[c * 4 + 3] = options.colors[c].a;
  36814. }
  36815. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  36816. }
  36817. if (options.uvs) {
  36818. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36819. for (var i = 0; i < options.uvs.length; i++) {
  36820. uvs[i * 2] = options.uvs[i].x;
  36821. uvs[i * 2 + 1] = options.uvs[i].y;
  36822. }
  36823. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  36824. }
  36825. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  36826. var indices = instance.getIndices();
  36827. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  36828. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  36829. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  36830. if (instance._closePath) {
  36831. var indexFirst = 0;
  36832. var indexLast = 0;
  36833. for (var p = 0; p < pathArray.length; p++) {
  36834. indexFirst = instance._idx[p] * 3;
  36835. if (p + 1 < pathArray.length) {
  36836. indexLast = (instance._idx[p + 1] - 1) * 3;
  36837. }
  36838. else {
  36839. indexLast = normals.length - 3;
  36840. }
  36841. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36842. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36843. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36844. normals[indexLast] = normals[indexFirst];
  36845. normals[indexLast + 1] = normals[indexFirst + 1];
  36846. normals[indexLast + 2] = normals[indexFirst + 2];
  36847. }
  36848. }
  36849. if (!(instance.areNormalsFrozen)) {
  36850. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  36851. }
  36852. }
  36853. return instance;
  36854. }
  36855. else {
  36856. var ribbon = new BABYLON.Mesh(name, scene);
  36857. ribbon.sideOrientation = sideOrientation;
  36858. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  36859. if (closePath) {
  36860. ribbon._idx = vertexData._idx;
  36861. }
  36862. ribbon._closePath = closePath;
  36863. ribbon._closeArray = closeArray;
  36864. vertexData.applyToMesh(ribbon, updatable);
  36865. return ribbon;
  36866. }
  36867. };
  36868. /**
  36869. * Creates a cylinder or a cone mesh.
  36870. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  36871. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  36872. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  36873. * 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.
  36874. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  36875. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  36876. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  36877. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  36878. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  36879. * 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).
  36880. * 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
  36881. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  36882. * 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
  36883. * 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.
  36884. * If `enclose` is false, a ring surface is one element.
  36885. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  36886. * 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
  36887. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36888. * 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).
  36889. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  36890. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  36891. */
  36892. MeshBuilder.CreateCylinder = function (name, options, scene) {
  36893. var cylinder = new BABYLON.Mesh(name, scene);
  36894. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  36895. cylinder.sideOrientation = options.sideOrientation;
  36896. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  36897. vertexData.applyToMesh(cylinder, options.updatable);
  36898. return cylinder;
  36899. };
  36900. /**
  36901. * Creates a torus mesh.
  36902. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  36903. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  36904. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  36905. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  36906. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36907. * 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).
  36908. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  36909. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  36910. */
  36911. MeshBuilder.CreateTorus = function (name, options, scene) {
  36912. var torus = new BABYLON.Mesh(name, scene);
  36913. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  36914. torus.sideOrientation = options.sideOrientation;
  36915. var vertexData = BABYLON.VertexData.CreateTorus(options);
  36916. vertexData.applyToMesh(torus, options.updatable);
  36917. return torus;
  36918. };
  36919. /**
  36920. * Creates a torus knot mesh.
  36921. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  36922. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  36923. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  36924. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  36925. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  36926. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36927. * 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).
  36928. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  36929. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  36930. */
  36931. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  36932. var torusKnot = new BABYLON.Mesh(name, scene);
  36933. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  36934. torusKnot.sideOrientation = options.sideOrientation;
  36935. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  36936. vertexData.applyToMesh(torusKnot, options.updatable);
  36937. return torusKnot;
  36938. };
  36939. /**
  36940. * Creates a line system mesh.
  36941. * A line system is a pool of many lines gathered in a single mesh.
  36942. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  36943. * 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.
  36944. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  36945. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  36946. * 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
  36947. * 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
  36948. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  36949. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  36950. */
  36951. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  36952. var instance = options.instance;
  36953. var lines = options.lines;
  36954. if (instance) {
  36955. var positionFunction = function (positions) {
  36956. var i = 0;
  36957. for (var l = 0; l < lines.length; l++) {
  36958. var points = lines[l];
  36959. for (var p = 0; p < points.length; p++) {
  36960. positions[i] = points[p].x;
  36961. positions[i + 1] = points[p].y;
  36962. positions[i + 2] = points[p].z;
  36963. i += 3;
  36964. }
  36965. }
  36966. };
  36967. instance.updateMeshPositions(positionFunction, false);
  36968. return instance;
  36969. }
  36970. // line system creation
  36971. var lineSystem = new BABYLON.LinesMesh(name, scene);
  36972. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  36973. vertexData.applyToMesh(lineSystem, options.updatable);
  36974. return lineSystem;
  36975. };
  36976. /**
  36977. * Creates a line mesh.
  36978. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  36979. * 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.
  36980. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  36981. * The parameter `points` is an array successive Vector3.
  36982. * 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
  36983. * When updating an instance, remember that only point positions can change, not the number of points.
  36984. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  36985. */
  36986. MeshBuilder.CreateLines = function (name, options, scene) {
  36987. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  36988. return lines;
  36989. };
  36990. /**
  36991. * Creates a dashed line mesh.
  36992. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  36993. * 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.
  36994. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  36995. * The parameter `points` is an array successive Vector3.
  36996. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  36997. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  36998. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  36999. * 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
  37000. * When updating an instance, remember that only point positions can change, not the number of points.
  37001. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37002. */
  37003. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  37004. var points = options.points;
  37005. var instance = options.instance;
  37006. var gapSize = options.gapSize;
  37007. var dashNb = options.dashNb;
  37008. var dashSize = options.dashSize;
  37009. if (instance) {
  37010. var positionFunction = function (positions) {
  37011. var curvect = BABYLON.Vector3.Zero();
  37012. var nbSeg = positions.length / 6;
  37013. var lg = 0;
  37014. var nb = 0;
  37015. var shft = 0;
  37016. var dashshft = 0;
  37017. var curshft = 0;
  37018. var p = 0;
  37019. var i = 0;
  37020. var j = 0;
  37021. for (i = 0; i < points.length - 1; i++) {
  37022. points[i + 1].subtractToRef(points[i], curvect);
  37023. lg += curvect.length();
  37024. }
  37025. shft = lg / nbSeg;
  37026. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  37027. for (i = 0; i < points.length - 1; i++) {
  37028. points[i + 1].subtractToRef(points[i], curvect);
  37029. nb = Math.floor(curvect.length() / shft);
  37030. curvect.normalize();
  37031. j = 0;
  37032. while (j < nb && p < positions.length) {
  37033. curshft = shft * j;
  37034. positions[p] = points[i].x + curshft * curvect.x;
  37035. positions[p + 1] = points[i].y + curshft * curvect.y;
  37036. positions[p + 2] = points[i].z + curshft * curvect.z;
  37037. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  37038. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  37039. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  37040. p += 6;
  37041. j++;
  37042. }
  37043. }
  37044. while (p < positions.length) {
  37045. positions[p] = points[i].x;
  37046. positions[p + 1] = points[i].y;
  37047. positions[p + 2] = points[i].z;
  37048. p += 3;
  37049. }
  37050. };
  37051. instance.updateMeshPositions(positionFunction, false);
  37052. return instance;
  37053. }
  37054. // dashed lines creation
  37055. var dashedLines = new BABYLON.LinesMesh(name, scene);
  37056. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  37057. vertexData.applyToMesh(dashedLines, options.updatable);
  37058. dashedLines.dashSize = dashSize;
  37059. dashedLines.gapSize = gapSize;
  37060. return dashedLines;
  37061. };
  37062. /**
  37063. * Creates an extruded shape mesh.
  37064. * 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.
  37065. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  37066. *
  37067. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  37068. * 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
  37069. * extruded along the Z axis.
  37070. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  37071. * 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.
  37072. * The parameter `scale` (float, default 1) is the value to scale the shape.
  37073. * 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
  37074. * 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
  37075. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  37076. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37077. * 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).
  37078. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37079. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  37080. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37081. */
  37082. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  37083. var path = options.path;
  37084. var shape = options.shape;
  37085. var scale = options.scale || 1;
  37086. var rotation = options.rotation || 0;
  37087. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  37088. var updatable = options.updatable;
  37089. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37090. var instance = options.instance;
  37091. var invertUV = options.invertUV || false;
  37092. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  37093. };
  37094. /**
  37095. * Creates an custom extruded shape mesh.
  37096. * 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.
  37097. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  37098. *
  37099. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  37100. * 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
  37101. * extruded along the Z axis.
  37102. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  37103. * 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
  37104. * and the distance of this point from the begining of the path :
  37105. * ```javascript
  37106. * var rotationFunction = function(i, distance) {
  37107. * // do things
  37108. * return rotationValue; }
  37109. * ```
  37110. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  37111. * 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
  37112. * and the distance of this point from the begining of the path :
  37113. * ```javascript
  37114. * var scaleFunction = function(i, distance) {
  37115. * // do things
  37116. * return scaleValue;}
  37117. * ```
  37118. * It must returns a float value that will be the scale value applied to the shape on each path point.
  37119. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  37120. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  37121. * 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
  37122. * 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
  37123. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  37124. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37125. * 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).
  37126. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37127. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  37128. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37129. */
  37130. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  37131. var path = options.path;
  37132. var shape = options.shape;
  37133. var scaleFunction = options.scaleFunction || (function () { return 1; });
  37134. var rotationFunction = options.rotationFunction || (function () { return 0; });
  37135. var ribbonCloseArray = options.ribbonCloseArray || false;
  37136. var ribbonClosePath = options.ribbonClosePath || false;
  37137. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  37138. var updatable = options.updatable;
  37139. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37140. var instance = options.instance;
  37141. var invertUV = options.invertUV || false;
  37142. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  37143. };
  37144. /**
  37145. * Creates lathe mesh.
  37146. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  37147. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  37148. *
  37149. * 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
  37150. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  37151. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  37152. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  37153. * 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.
  37154. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  37155. * 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
  37156. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37157. * 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).
  37158. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37159. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  37160. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37161. */
  37162. MeshBuilder.CreateLathe = function (name, options, scene) {
  37163. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  37164. var closed = (options.closed === undefined) ? true : options.closed;
  37165. var shape = options.shape;
  37166. var radius = options.radius || 1;
  37167. var tessellation = options.tessellation || 64;
  37168. var updatable = options.updatable;
  37169. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37170. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  37171. var pi2 = Math.PI * 2;
  37172. var paths = new Array();
  37173. var invertUV = options.invertUV || false;
  37174. var i = 0;
  37175. var p = 0;
  37176. var step = pi2 / tessellation * arc;
  37177. var rotated;
  37178. var path = new Array();
  37179. ;
  37180. for (i = 0; i <= tessellation; i++) {
  37181. var path = [];
  37182. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  37183. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  37184. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  37185. }
  37186. for (p = 0; p < shape.length; p++) {
  37187. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  37188. path.push(rotated);
  37189. }
  37190. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  37191. 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));
  37192. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  37193. }
  37194. paths.push(path);
  37195. }
  37196. // lathe ribbon
  37197. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  37198. return lathe;
  37199. };
  37200. /**
  37201. * Creates a plane mesh.
  37202. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  37203. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  37204. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  37205. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  37206. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37207. * 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).
  37208. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37209. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37210. */
  37211. MeshBuilder.CreatePlane = function (name, options, scene) {
  37212. var plane = new BABYLON.Mesh(name, scene);
  37213. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37214. plane.sideOrientation = options.sideOrientation;
  37215. var vertexData = BABYLON.VertexData.CreatePlane(options);
  37216. vertexData.applyToMesh(plane, options.updatable);
  37217. if (options.sourcePlane) {
  37218. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  37219. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  37220. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  37221. plane.rotate(vectorProduct, product);
  37222. }
  37223. return plane;
  37224. };
  37225. /**
  37226. * Creates a ground mesh.
  37227. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  37228. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  37229. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  37230. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37231. */
  37232. MeshBuilder.CreateGround = function (name, options, scene) {
  37233. var ground = new BABYLON.GroundMesh(name, scene);
  37234. ground._setReady(false);
  37235. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37236. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37237. ground._width = options.width || 1;
  37238. ground._height = options.height || 1;
  37239. ground._maxX = ground._width / 2;
  37240. ground._maxZ = ground._height / 2;
  37241. ground._minX = -ground._maxX;
  37242. ground._minZ = -ground._maxZ;
  37243. var vertexData = BABYLON.VertexData.CreateGround(options);
  37244. vertexData.applyToMesh(ground, options.updatable);
  37245. ground._setReady(true);
  37246. return ground;
  37247. };
  37248. /**
  37249. * Creates a tiled ground mesh.
  37250. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  37251. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  37252. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  37253. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  37254. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  37255. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  37256. * numbers of subdivisions on the ground width and height of each tile.
  37257. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37258. */
  37259. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  37260. var tiledGround = new BABYLON.Mesh(name, scene);
  37261. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  37262. vertexData.applyToMesh(tiledGround, options.updatable);
  37263. return tiledGround;
  37264. };
  37265. /**
  37266. * Creates a ground mesh from a height map.
  37267. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  37268. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  37269. * The parameter `url` sets the URL of the height map image resource.
  37270. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  37271. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  37272. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  37273. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  37274. * 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.
  37275. * 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).
  37276. * This function is passed the newly built mesh :
  37277. * ```javascript
  37278. * function(mesh) { // do things
  37279. * return; }
  37280. * ```
  37281. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37282. */
  37283. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  37284. var width = options.width || 10.0;
  37285. var height = options.height || 10.0;
  37286. var subdivisions = options.subdivisions || 1 | 0;
  37287. var minHeight = options.minHeight || 0.0;
  37288. var maxHeight = options.maxHeight || 10.0;
  37289. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37290. var updatable = options.updatable;
  37291. var onReady = options.onReady;
  37292. var ground = new BABYLON.GroundMesh(name, scene);
  37293. ground._subdivisionsX = subdivisions;
  37294. ground._subdivisionsY = subdivisions;
  37295. ground._width = width;
  37296. ground._height = height;
  37297. ground._maxX = ground._width / 2.0;
  37298. ground._maxZ = ground._height / 2.0;
  37299. ground._minX = -ground._maxX;
  37300. ground._minZ = -ground._maxZ;
  37301. ground._setReady(false);
  37302. var onload = function (img) {
  37303. // Getting height map data
  37304. var canvas = document.createElement("canvas");
  37305. var context = canvas.getContext("2d");
  37306. var bufferWidth = img.width;
  37307. var bufferHeight = img.height;
  37308. canvas.width = bufferWidth;
  37309. canvas.height = bufferHeight;
  37310. context.drawImage(img, 0, 0);
  37311. // Create VertexData from map data
  37312. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  37313. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  37314. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  37315. width: width, height: height,
  37316. subdivisions: subdivisions,
  37317. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  37318. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  37319. });
  37320. vertexData.applyToMesh(ground, updatable);
  37321. ground._setReady(true);
  37322. //execute ready callback, if set
  37323. if (onReady) {
  37324. onReady(ground);
  37325. }
  37326. };
  37327. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  37328. return ground;
  37329. };
  37330. /**
  37331. * Creates a polygon mesh.
  37332. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  37333. * 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.
  37334. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37335. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37336. * 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).
  37337. * Remember you can only change the shape positions, not their number when updating a polygon.
  37338. */
  37339. MeshBuilder.CreatePolygon = function (name, options, scene) {
  37340. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37341. var shape = options.shape;
  37342. var holes = options.holes || [];
  37343. var depth = options.depth || 0;
  37344. var contours = [];
  37345. var hole = [];
  37346. for (var i = 0; i < shape.length; i++) {
  37347. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  37348. }
  37349. var epsilon = 0.00000001;
  37350. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  37351. contours.pop();
  37352. }
  37353. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  37354. for (var hNb = 0; hNb < holes.length; hNb++) {
  37355. hole = [];
  37356. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  37357. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  37358. }
  37359. polygonTriangulation.addHole(hole);
  37360. }
  37361. var polygon = polygonTriangulation.build(options.updatable, depth);
  37362. polygon.sideOrientation = options.sideOrientation;
  37363. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  37364. vertexData.applyToMesh(polygon, options.updatable);
  37365. return polygon;
  37366. };
  37367. ;
  37368. /**
  37369. * Creates an extruded polygon mesh, with depth in the Y direction.
  37370. * 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).
  37371. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  37372. */
  37373. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  37374. return MeshBuilder.CreatePolygon(name, options, scene);
  37375. };
  37376. ;
  37377. /**
  37378. * Creates a tube mesh.
  37379. * 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.
  37380. *
  37381. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  37382. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  37383. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  37384. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  37385. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  37386. * 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.
  37387. * It must return a radius value (positive float) :
  37388. * ```javascript
  37389. * var radiusFunction = function(i, distance) {
  37390. * // do things
  37391. * return radius; }
  37392. * ```
  37393. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  37394. * 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
  37395. * 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
  37396. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37397. * 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).
  37398. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37399. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  37400. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37401. */
  37402. MeshBuilder.CreateTube = function (name, options, scene) {
  37403. var path = options.path;
  37404. var radius = options.radius || 1.0;
  37405. var tessellation = options.tessellation || 64 | 0;
  37406. var radiusFunction = options.radiusFunction;
  37407. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  37408. var invertUV = options.invertUV || false;
  37409. var updatable = options.updatable;
  37410. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37411. var instance = options.instance;
  37412. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  37413. // tube geometry
  37414. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  37415. var tangents = path3D.getTangents();
  37416. var normals = path3D.getNormals();
  37417. var distances = path3D.getDistances();
  37418. var pi2 = Math.PI * 2;
  37419. var step = pi2 / tessellation * arc;
  37420. var returnRadius = function () { return radius; };
  37421. var radiusFunctionFinal = radiusFunction || returnRadius;
  37422. var circlePath;
  37423. var rad;
  37424. var normal;
  37425. var rotated;
  37426. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  37427. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  37428. for (var i = 0; i < path.length; i++) {
  37429. rad = radiusFunctionFinal(i, distances[i]); // current radius
  37430. circlePath = Array(); // current circle array
  37431. normal = normals[i]; // current normal
  37432. for (var t = 0; t < tessellation; t++) {
  37433. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  37434. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  37435. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  37436. rotated.scaleInPlace(rad).addInPlace(path[i]);
  37437. circlePath[t] = rotated;
  37438. }
  37439. circlePaths[index] = circlePath;
  37440. index++;
  37441. }
  37442. // cap
  37443. var capPath = function (nbPoints, pathIndex) {
  37444. var pointCap = Array();
  37445. for (var i = 0; i < nbPoints; i++) {
  37446. pointCap.push(path[pathIndex]);
  37447. }
  37448. return pointCap;
  37449. };
  37450. switch (cap) {
  37451. case BABYLON.Mesh.NO_CAP:
  37452. break;
  37453. case BABYLON.Mesh.CAP_START:
  37454. circlePaths[0] = capPath(tessellation, 0);
  37455. circlePaths[1] = circlePaths[2].slice(0);
  37456. break;
  37457. case BABYLON.Mesh.CAP_END:
  37458. circlePaths[index] = circlePaths[index - 1].slice(0);
  37459. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  37460. break;
  37461. case BABYLON.Mesh.CAP_ALL:
  37462. circlePaths[0] = capPath(tessellation, 0);
  37463. circlePaths[1] = circlePaths[2].slice(0);
  37464. circlePaths[index] = circlePaths[index - 1].slice(0);
  37465. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  37466. break;
  37467. default:
  37468. break;
  37469. }
  37470. return circlePaths;
  37471. };
  37472. var path3D;
  37473. var pathArray;
  37474. if (instance) {
  37475. var arc = options.arc || instance.arc;
  37476. path3D = (instance.path3D).update(path);
  37477. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  37478. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  37479. instance.path3D = path3D;
  37480. instance.pathArray = pathArray;
  37481. instance.arc = arc;
  37482. return instance;
  37483. }
  37484. // tube creation
  37485. path3D = new BABYLON.Path3D(path);
  37486. var newPathArray = new Array();
  37487. cap = (cap < 0 || cap > 3) ? 0 : cap;
  37488. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  37489. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  37490. tube.pathArray = pathArray;
  37491. tube.path3D = path3D;
  37492. tube.tessellation = tessellation;
  37493. tube.cap = cap;
  37494. tube.arc = options.arc;
  37495. return tube;
  37496. };
  37497. /**
  37498. * Creates a polyhedron mesh.
  37499. *
  37500. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  37501. * 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
  37502. * to choose the wanted type.
  37503. * The parameter `size` (positive float, default 1) sets the polygon size.
  37504. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  37505. * 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`.
  37506. * 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
  37507. * 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)`).
  37508. * 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
  37509. * 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.
  37510. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37511. * 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).
  37512. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  37513. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  37514. */
  37515. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  37516. var polyhedron = new BABYLON.Mesh(name, scene);
  37517. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  37518. polyhedron.sideOrientation = options.sideOrientation;
  37519. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  37520. vertexData.applyToMesh(polyhedron, options.updatable);
  37521. return polyhedron;
  37522. };
  37523. /**
  37524. * Creates a decal mesh.
  37525. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  37526. * 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.
  37527. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  37528. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  37529. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  37530. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  37531. */
  37532. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  37533. var indices = sourceMesh.getIndices();
  37534. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37535. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37536. var position = options.position || BABYLON.Vector3.Zero();
  37537. var normal = options.normal || BABYLON.Vector3.Up();
  37538. var size = options.size || BABYLON.Vector3.One();
  37539. var angle = options.angle || 0;
  37540. // Getting correct rotation
  37541. if (!normal) {
  37542. var target = new BABYLON.Vector3(0, 0, 1);
  37543. var camera = sourceMesh.getScene().activeCamera;
  37544. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  37545. normal = camera.globalPosition.subtract(cameraWorldTarget);
  37546. }
  37547. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  37548. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  37549. var pitch = Math.atan2(normal.y, len);
  37550. // Matrix
  37551. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  37552. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  37553. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  37554. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  37555. var vertexData = new BABYLON.VertexData();
  37556. vertexData.indices = [];
  37557. vertexData.positions = [];
  37558. vertexData.normals = [];
  37559. vertexData.uvs = [];
  37560. var currentVertexDataIndex = 0;
  37561. var extractDecalVector3 = function (indexId) {
  37562. var vertexId = indices[indexId];
  37563. var result = new BABYLON.PositionNormalVertex();
  37564. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  37565. // Send vector to decal local world
  37566. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  37567. // Get normal
  37568. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  37569. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  37570. return result;
  37571. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  37572. var clip = function (vertices, axis) {
  37573. if (vertices.length === 0) {
  37574. return vertices;
  37575. }
  37576. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  37577. var clipVertices = function (v0, v1) {
  37578. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  37579. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  37580. };
  37581. var result = new Array();
  37582. for (var index = 0; index < vertices.length; index += 3) {
  37583. var v1Out;
  37584. var v2Out;
  37585. var v3Out;
  37586. var total = 0;
  37587. var nV1, nV2, nV3, nV4;
  37588. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  37589. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  37590. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  37591. v1Out = d1 > 0;
  37592. v2Out = d2 > 0;
  37593. v3Out = d3 > 0;
  37594. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  37595. switch (total) {
  37596. case 0:
  37597. result.push(vertices[index]);
  37598. result.push(vertices[index + 1]);
  37599. result.push(vertices[index + 2]);
  37600. break;
  37601. case 1:
  37602. if (v1Out) {
  37603. nV1 = vertices[index + 1];
  37604. nV2 = vertices[index + 2];
  37605. nV3 = clipVertices(vertices[index], nV1);
  37606. nV4 = clipVertices(vertices[index], nV2);
  37607. }
  37608. if (v2Out) {
  37609. nV1 = vertices[index];
  37610. nV2 = vertices[index + 2];
  37611. nV3 = clipVertices(vertices[index + 1], nV1);
  37612. nV4 = clipVertices(vertices[index + 1], nV2);
  37613. result.push(nV3);
  37614. result.push(nV2.clone());
  37615. result.push(nV1.clone());
  37616. result.push(nV2.clone());
  37617. result.push(nV3.clone());
  37618. result.push(nV4);
  37619. break;
  37620. }
  37621. if (v3Out) {
  37622. nV1 = vertices[index];
  37623. nV2 = vertices[index + 1];
  37624. nV3 = clipVertices(vertices[index + 2], nV1);
  37625. nV4 = clipVertices(vertices[index + 2], nV2);
  37626. }
  37627. result.push(nV1.clone());
  37628. result.push(nV2.clone());
  37629. result.push(nV3);
  37630. result.push(nV4);
  37631. result.push(nV3.clone());
  37632. result.push(nV2.clone());
  37633. break;
  37634. case 2:
  37635. if (!v1Out) {
  37636. nV1 = vertices[index].clone();
  37637. nV2 = clipVertices(nV1, vertices[index + 1]);
  37638. nV3 = clipVertices(nV1, vertices[index + 2]);
  37639. result.push(nV1);
  37640. result.push(nV2);
  37641. result.push(nV3);
  37642. }
  37643. if (!v2Out) {
  37644. nV1 = vertices[index + 1].clone();
  37645. nV2 = clipVertices(nV1, vertices[index + 2]);
  37646. nV3 = clipVertices(nV1, vertices[index]);
  37647. result.push(nV1);
  37648. result.push(nV2);
  37649. result.push(nV3);
  37650. }
  37651. if (!v3Out) {
  37652. nV1 = vertices[index + 2].clone();
  37653. nV2 = clipVertices(nV1, vertices[index]);
  37654. nV3 = clipVertices(nV1, vertices[index + 1]);
  37655. result.push(nV1);
  37656. result.push(nV2);
  37657. result.push(nV3);
  37658. }
  37659. break;
  37660. case 3:
  37661. break;
  37662. }
  37663. }
  37664. return result;
  37665. };
  37666. for (var index = 0; index < indices.length; index += 3) {
  37667. var faceVertices = new Array();
  37668. faceVertices.push(extractDecalVector3(index));
  37669. faceVertices.push(extractDecalVector3(index + 1));
  37670. faceVertices.push(extractDecalVector3(index + 2));
  37671. // Clip
  37672. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  37673. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  37674. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  37675. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  37676. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  37677. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  37678. if (faceVertices.length === 0) {
  37679. continue;
  37680. }
  37681. // Add UVs and get back to world
  37682. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  37683. var vertex = faceVertices[vIndex];
  37684. //TODO check for Int32Array | Uint32Array | Uint16Array
  37685. vertexData.indices.push(currentVertexDataIndex);
  37686. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  37687. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  37688. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  37689. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  37690. currentVertexDataIndex++;
  37691. }
  37692. }
  37693. // Return mesh
  37694. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  37695. vertexData.applyToMesh(decal);
  37696. decal.position = position.clone();
  37697. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  37698. return decal;
  37699. };
  37700. // Privates
  37701. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  37702. // extrusion geometry
  37703. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  37704. var tangents = path3D.getTangents();
  37705. var normals = path3D.getNormals();
  37706. var binormals = path3D.getBinormals();
  37707. var distances = path3D.getDistances();
  37708. var angle = 0;
  37709. var returnScale = function () { return scale; };
  37710. var returnRotation = function () { return rotation; };
  37711. var rotate = custom ? rotateFunction : returnRotation;
  37712. var scl = custom ? scaleFunction : returnScale;
  37713. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  37714. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  37715. for (var i = 0; i < curve.length; i++) {
  37716. var shapePath = new Array();
  37717. var angleStep = rotate(i, distances[i]);
  37718. var scaleRatio = scl(i, distances[i]);
  37719. for (var p = 0; p < shape.length; p++) {
  37720. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  37721. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  37722. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  37723. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  37724. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  37725. shapePath[p] = rotated;
  37726. }
  37727. shapePaths[index] = shapePath;
  37728. angle += angleStep;
  37729. index++;
  37730. }
  37731. // cap
  37732. var capPath = function (shapePath) {
  37733. var pointCap = Array();
  37734. var barycenter = BABYLON.Vector3.Zero();
  37735. var i;
  37736. for (i = 0; i < shapePath.length; i++) {
  37737. barycenter.addInPlace(shapePath[i]);
  37738. }
  37739. barycenter.scaleInPlace(1.0 / shapePath.length);
  37740. for (i = 0; i < shapePath.length; i++) {
  37741. pointCap.push(barycenter);
  37742. }
  37743. return pointCap;
  37744. };
  37745. switch (cap) {
  37746. case BABYLON.Mesh.NO_CAP:
  37747. break;
  37748. case BABYLON.Mesh.CAP_START:
  37749. shapePaths[0] = capPath(shapePaths[2]);
  37750. shapePaths[1] = shapePaths[2];
  37751. break;
  37752. case BABYLON.Mesh.CAP_END:
  37753. shapePaths[index] = shapePaths[index - 1];
  37754. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  37755. break;
  37756. case BABYLON.Mesh.CAP_ALL:
  37757. shapePaths[0] = capPath(shapePaths[2]);
  37758. shapePaths[1] = shapePaths[2];
  37759. shapePaths[index] = shapePaths[index - 1];
  37760. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  37761. break;
  37762. default:
  37763. break;
  37764. }
  37765. return shapePaths;
  37766. };
  37767. var path3D;
  37768. var pathArray;
  37769. if (instance) {
  37770. path3D = (instance.path3D).update(curve);
  37771. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  37772. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  37773. return instance;
  37774. }
  37775. // extruded shape creation
  37776. path3D = new BABYLON.Path3D(curve);
  37777. var newShapePaths = new Array();
  37778. cap = (cap < 0 || cap > 3) ? 0 : cap;
  37779. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  37780. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  37781. extrudedGeneric.pathArray = pathArray;
  37782. extrudedGeneric.path3D = path3D;
  37783. extrudedGeneric.cap = cap;
  37784. return extrudedGeneric;
  37785. };
  37786. return MeshBuilder;
  37787. }());
  37788. BABYLON.MeshBuilder = MeshBuilder;
  37789. })(BABYLON || (BABYLON = {}));
  37790. //# sourceMappingURL=babylon.meshBuilder.js.map
  37791. var BABYLON;
  37792. (function (BABYLON) {
  37793. var Layer = (function () {
  37794. function Layer(name, imgUrl, scene, isBackground, color) {
  37795. this.name = name;
  37796. this.scale = new BABYLON.Vector2(1, 1);
  37797. this.offset = new BABYLON.Vector2(0, 0);
  37798. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  37799. this.layerMask = 0x0FFFFFFF;
  37800. this._vertexBuffers = {};
  37801. // Events
  37802. /**
  37803. * An event triggered when the layer is disposed.
  37804. * @type {BABYLON.Observable}
  37805. */
  37806. this.onDisposeObservable = new BABYLON.Observable();
  37807. /**
  37808. * An event triggered before rendering the scene
  37809. * @type {BABYLON.Observable}
  37810. */
  37811. this.onBeforeRenderObservable = new BABYLON.Observable();
  37812. /**
  37813. * An event triggered after rendering the scene
  37814. * @type {BABYLON.Observable}
  37815. */
  37816. this.onAfterRenderObservable = new BABYLON.Observable();
  37817. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  37818. this.isBackground = isBackground === undefined ? true : isBackground;
  37819. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  37820. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  37821. this._scene.layers.push(this);
  37822. var engine = this._scene.getEngine();
  37823. // VBO
  37824. var vertices = [];
  37825. vertices.push(1, 1);
  37826. vertices.push(-1, 1);
  37827. vertices.push(-1, -1);
  37828. vertices.push(1, -1);
  37829. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  37830. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  37831. // Indices
  37832. var indices = [];
  37833. indices.push(0);
  37834. indices.push(1);
  37835. indices.push(2);
  37836. indices.push(0);
  37837. indices.push(2);
  37838. indices.push(3);
  37839. this._indexBuffer = engine.createIndexBuffer(indices);
  37840. // Effects
  37841. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  37842. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  37843. }
  37844. Object.defineProperty(Layer.prototype, "onDispose", {
  37845. set: function (callback) {
  37846. if (this._onDisposeObserver) {
  37847. this.onDisposeObservable.remove(this._onDisposeObserver);
  37848. }
  37849. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  37850. },
  37851. enumerable: true,
  37852. configurable: true
  37853. });
  37854. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  37855. set: function (callback) {
  37856. if (this._onBeforeRenderObserver) {
  37857. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  37858. }
  37859. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  37860. },
  37861. enumerable: true,
  37862. configurable: true
  37863. });
  37864. Object.defineProperty(Layer.prototype, "onAfterRender", {
  37865. set: function (callback) {
  37866. if (this._onAfterRenderObserver) {
  37867. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  37868. }
  37869. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  37870. },
  37871. enumerable: true,
  37872. configurable: true
  37873. });
  37874. Layer.prototype.render = function () {
  37875. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  37876. // Check
  37877. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  37878. return;
  37879. var engine = this._scene.getEngine();
  37880. this.onBeforeRenderObservable.notifyObservers(this);
  37881. // Render
  37882. engine.enableEffect(currentEffect);
  37883. engine.setState(false);
  37884. // Texture
  37885. currentEffect.setTexture("textureSampler", this.texture);
  37886. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  37887. // Color
  37888. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  37889. // Scale / offset
  37890. currentEffect.setVector2("offset", this.offset);
  37891. currentEffect.setVector2("scale", this.scale);
  37892. // VBOs
  37893. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  37894. // Draw order
  37895. if (!this.alphaTest) {
  37896. engine.setAlphaMode(this.alphaBlendingMode);
  37897. engine.draw(true, 0, 6);
  37898. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  37899. }
  37900. else {
  37901. engine.draw(true, 0, 6);
  37902. }
  37903. this.onAfterRenderObservable.notifyObservers(this);
  37904. };
  37905. Layer.prototype.dispose = function () {
  37906. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37907. if (vertexBuffer) {
  37908. vertexBuffer.dispose();
  37909. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  37910. }
  37911. if (this._indexBuffer) {
  37912. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37913. this._indexBuffer = null;
  37914. }
  37915. if (this.texture) {
  37916. this.texture.dispose();
  37917. this.texture = null;
  37918. }
  37919. // Remove from scene
  37920. var index = this._scene.layers.indexOf(this);
  37921. this._scene.layers.splice(index, 1);
  37922. // Callback
  37923. this.onDisposeObservable.notifyObservers(this);
  37924. this.onDisposeObservable.clear();
  37925. this.onAfterRenderObservable.clear();
  37926. this.onBeforeRenderObservable.clear();
  37927. };
  37928. return Layer;
  37929. }());
  37930. BABYLON.Layer = Layer;
  37931. })(BABYLON || (BABYLON = {}));
  37932. //# sourceMappingURL=babylon.layer.js.map
  37933. var BABYLON;
  37934. (function (BABYLON) {
  37935. var BlurPostProcess = (function (_super) {
  37936. __extends(BlurPostProcess, _super);
  37937. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  37938. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  37939. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  37940. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  37941. _this.direction = direction;
  37942. _this.onApplyObservable.add(function (effect) {
  37943. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  37944. });
  37945. _this.kernel = kernel;
  37946. return _this;
  37947. }
  37948. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  37949. /**
  37950. * Gets the length in pixels of the blur sample region
  37951. */
  37952. get: function () {
  37953. return this._idealKernel;
  37954. },
  37955. /**
  37956. * Sets the length in pixels of the blur sample region
  37957. */
  37958. set: function (v) {
  37959. if (this._idealKernel === v) {
  37960. return;
  37961. }
  37962. v = Math.max(v, 1);
  37963. this._idealKernel = v;
  37964. this._kernel = this._nearestBestKernel(v);
  37965. this._updateParameters();
  37966. },
  37967. enumerable: true,
  37968. configurable: true
  37969. });
  37970. BlurPostProcess.prototype._updateParameters = function () {
  37971. // Generate sampling offsets and weights
  37972. var N = this._kernel;
  37973. var centerIndex = (N - 1) / 2;
  37974. // Generate Gaussian sampling weights over kernel
  37975. var offsets = [];
  37976. var weights = [];
  37977. var totalWeight = 0;
  37978. for (var i = 0; i < N; i++) {
  37979. var u = i / (N - 1);
  37980. var w = this._gaussianWeight(u * 2.0 - 1);
  37981. offsets[i] = (i - centerIndex);
  37982. weights[i] = w;
  37983. totalWeight += w;
  37984. }
  37985. // Normalize weights
  37986. for (var i = 0; i < weights.length; i++) {
  37987. weights[i] /= totalWeight;
  37988. }
  37989. // Optimize: combine samples to take advantage of hardware linear sampling
  37990. // Walk from left to center, combining pairs (symmetrically)
  37991. var linearSamplingWeights = [];
  37992. var linearSamplingOffsets = [];
  37993. var linearSamplingMap = [];
  37994. for (var i = 0; i <= centerIndex; i += 2) {
  37995. var j = Math.min(i + 1, Math.floor(centerIndex));
  37996. var singleCenterSample = i === j;
  37997. if (singleCenterSample) {
  37998. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  37999. }
  38000. else {
  38001. var sharedCell = j === centerIndex;
  38002. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  38003. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  38004. if (offsetLinear === 0) {
  38005. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  38006. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  38007. }
  38008. else {
  38009. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  38010. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  38011. }
  38012. }
  38013. }
  38014. for (var i = 0; i < linearSamplingMap.length; i++) {
  38015. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  38016. linearSamplingWeights[i] = linearSamplingMap[i].w;
  38017. }
  38018. // Replace with optimized
  38019. offsets = linearSamplingOffsets;
  38020. weights = linearSamplingWeights;
  38021. // Generate shaders
  38022. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  38023. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  38024. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  38025. var defines = "";
  38026. for (var i = 0; i < varyingCount; i++) {
  38027. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  38028. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  38029. }
  38030. var depCount = 0;
  38031. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  38032. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  38033. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  38034. depCount++;
  38035. }
  38036. this.updateEffect(defines, null, null, {
  38037. varyingCount: varyingCount,
  38038. depCount: depCount
  38039. });
  38040. };
  38041. /**
  38042. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  38043. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  38044. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  38045. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  38046. * The gaps between physical kernels are compensated for in the weighting of the samples
  38047. * @param idealKernel Ideal blur kernel.
  38048. * @return Nearest best kernel.
  38049. */
  38050. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  38051. var v = Math.round(idealKernel);
  38052. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  38053. var k = _a[_i];
  38054. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  38055. return Math.max(k, 3);
  38056. }
  38057. }
  38058. return Math.max(v, 3);
  38059. };
  38060. /**
  38061. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  38062. * @param x The point on the Gaussian distribution to sample.
  38063. * @return the value of the Gaussian function at x.
  38064. */
  38065. BlurPostProcess.prototype._gaussianWeight = function (x) {
  38066. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  38067. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  38068. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  38069. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  38070. // truncated at around 1.3% of peak strength.
  38071. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  38072. var sigma = (1 / 3);
  38073. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  38074. var exponent = -((x * x) / (2.0 * sigma * sigma));
  38075. var weight = (1.0 / denominator) * Math.exp(exponent);
  38076. return weight;
  38077. };
  38078. /**
  38079. * Generates a string that can be used as a floating point number in GLSL.
  38080. * @param x Value to print.
  38081. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  38082. * @return GLSL float string.
  38083. */
  38084. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  38085. if (decimalFigures === void 0) { decimalFigures = 8; }
  38086. return x.toFixed(decimalFigures).replace(/0+$/, '');
  38087. };
  38088. return BlurPostProcess;
  38089. }(BABYLON.PostProcess));
  38090. BABYLON.BlurPostProcess = BlurPostProcess;
  38091. })(BABYLON || (BABYLON = {}));
  38092. //# sourceMappingURL=babylon.blurPostProcess.js.map
  38093. var BABYLON;
  38094. (function (BABYLON) {
  38095. var FxaaPostProcess = (function (_super) {
  38096. __extends(FxaaPostProcess, _super);
  38097. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  38098. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  38099. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  38100. _this.onApplyObservable.add(function (effect) {
  38101. var texelSize = _this.texelSize;
  38102. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  38103. });
  38104. return _this;
  38105. }
  38106. return FxaaPostProcess;
  38107. }(BABYLON.PostProcess));
  38108. BABYLON.FxaaPostProcess = FxaaPostProcess;
  38109. })(BABYLON || (BABYLON = {}));
  38110. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  38111. var BABYLON;
  38112. (function (BABYLON) {
  38113. var HighlightsPostProcess = (function (_super) {
  38114. __extends(HighlightsPostProcess, _super);
  38115. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  38116. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  38117. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  38118. }
  38119. return HighlightsPostProcess;
  38120. }(BABYLON.PostProcess));
  38121. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  38122. })(BABYLON || (BABYLON = {}));
  38123. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  38124. var BABYLON;
  38125. (function (BABYLON) {
  38126. var ImageProcessingPostProcess = (function (_super) {
  38127. __extends(ImageProcessingPostProcess, _super);
  38128. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  38129. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  38130. var _this = _super.call(this, name, "imageProcessing", [
  38131. 'contrast',
  38132. 'vignetteSettings1',
  38133. 'vignetteSettings2',
  38134. 'cameraExposureLinear',
  38135. 'vCameraColorCurveNegative',
  38136. 'vCameraColorCurveNeutral',
  38137. 'vCameraColorCurvePositive',
  38138. 'colorTransformSettings'
  38139. ], ["txColorTransform"], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  38140. _this.colorGradingWeight = 1.0;
  38141. _this.colorCurves = new BABYLON.ColorCurves();
  38142. _this._colorCurvesEnabled = true;
  38143. _this.cameraFov = 0.5;
  38144. _this.vignetteStretch = 0;
  38145. _this.vignetteCentreX = 0;
  38146. _this.vignetteCentreY = 0;
  38147. _this.vignetteWeight = 1.5;
  38148. _this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  38149. _this._vignetteBlendMode = ImageProcessingPostProcess.VIGNETTEMODE_MULTIPLY;
  38150. _this._vignetteEnabled = true;
  38151. _this.cameraContrast = 1.0;
  38152. _this.cameraExposure = 1.68;
  38153. _this._cameraToneMappingEnabled = true;
  38154. _this._fromLinearSpace = false;
  38155. _this._updateParameters();
  38156. _this.onApply = function (effect) {
  38157. var aspectRatio = _this.aspectRatio;
  38158. // Color
  38159. if (_this._colorCurvesEnabled) {
  38160. BABYLON.ColorCurves.Bind(_this.colorCurves, effect);
  38161. }
  38162. if (_this._vignetteEnabled) {
  38163. // Vignette
  38164. var vignetteScaleY = Math.tan(_this.cameraFov * 0.5);
  38165. var vignetteScaleX = vignetteScaleY * aspectRatio;
  38166. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  38167. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, _this.vignetteStretch);
  38168. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, _this.vignetteStretch);
  38169. effect.setFloat4('vignetteSettings1', vignetteScaleX, vignetteScaleY, -vignetteScaleX * _this.vignetteCentreX, -vignetteScaleY * _this.vignetteCentreY);
  38170. var vignettePower = -2.0 * _this.vignetteWeight;
  38171. effect.setFloat4('vignetteSettings2', _this.vignetteColor.r, _this.vignetteColor.g, _this.vignetteColor.b, vignettePower);
  38172. }
  38173. // Contrast and exposure
  38174. effect.setFloat('contrast', _this.cameraContrast);
  38175. effect.setFloat('cameraExposureLinear', Math.pow(2.0, -_this.cameraExposure) * Math.PI);
  38176. // Color transform settings
  38177. if (_this._colorGradingTexture) {
  38178. effect.setTexture('txColorTransform', _this.colorGradingTexture);
  38179. var textureSize = _this.colorGradingTexture.getSize().height;
  38180. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  38181. 0.5 / textureSize, // textureOffset
  38182. textureSize, // textureSize
  38183. _this.colorGradingWeight // weight
  38184. );
  38185. }
  38186. };
  38187. return _this;
  38188. }
  38189. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  38190. get: function () {
  38191. return this._colorGradingTexture;
  38192. },
  38193. set: function (value) {
  38194. if (this._colorGradingTexture === value) {
  38195. return;
  38196. }
  38197. this._colorGradingTexture = value;
  38198. this._updateParameters();
  38199. },
  38200. enumerable: true,
  38201. configurable: true
  38202. });
  38203. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  38204. get: function () {
  38205. return this._vignetteBlendMode;
  38206. },
  38207. set: function (value) {
  38208. if (this._vignetteBlendMode === value) {
  38209. return;
  38210. }
  38211. this._vignetteBlendMode = value;
  38212. this._updateParameters();
  38213. },
  38214. enumerable: true,
  38215. configurable: true
  38216. });
  38217. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  38218. get: function () {
  38219. return this._colorCurvesEnabled;
  38220. },
  38221. set: function (value) {
  38222. if (this._colorCurvesEnabled === value) {
  38223. return;
  38224. }
  38225. this._colorCurvesEnabled = value;
  38226. this._updateParameters();
  38227. },
  38228. enumerable: true,
  38229. configurable: true
  38230. });
  38231. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  38232. get: function () {
  38233. return this._vignetteEnabled;
  38234. },
  38235. set: function (value) {
  38236. if (this._vignetteEnabled === value) {
  38237. return;
  38238. }
  38239. this._vignetteEnabled = value;
  38240. this._updateParameters();
  38241. },
  38242. enumerable: true,
  38243. configurable: true
  38244. });
  38245. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  38246. get: function () {
  38247. return this._fromLinearSpace;
  38248. },
  38249. set: function (value) {
  38250. if (this._fromLinearSpace === value) {
  38251. return;
  38252. }
  38253. this._fromLinearSpace = value;
  38254. this._updateParameters();
  38255. },
  38256. enumerable: true,
  38257. configurable: true
  38258. });
  38259. Object.defineProperty(ImageProcessingPostProcess.prototype, "cameraToneMappingEnabled", {
  38260. get: function () {
  38261. return this._cameraToneMappingEnabled;
  38262. },
  38263. set: function (value) {
  38264. if (this._cameraToneMappingEnabled === value) {
  38265. return;
  38266. }
  38267. this._cameraToneMappingEnabled = value;
  38268. this._updateParameters();
  38269. },
  38270. enumerable: true,
  38271. configurable: true
  38272. });
  38273. ImageProcessingPostProcess.prototype._updateParameters = function () {
  38274. var defines = "";
  38275. var samplers = ["textureSampler"];
  38276. if (this.colorGradingTexture) {
  38277. defines = "#define COLORGRADING\r\n";
  38278. samplers.push("txColorTransform");
  38279. }
  38280. if (this._vignetteEnabled) {
  38281. defines += "#define VIGNETTE\r\n";
  38282. if (this.vignetteBlendMode === ImageProcessingPostProcess._VIGNETTEMODE_MULTIPLY) {
  38283. defines += "#define VIGNETTEBLENDMODEMULTIPLY\r\n";
  38284. }
  38285. else {
  38286. defines += "#define VIGNETTEBLENDMODEOPAQUE\r\n";
  38287. }
  38288. }
  38289. if (this.cameraToneMappingEnabled) {
  38290. defines += "#define TONEMAPPING\r\n";
  38291. }
  38292. if (this._colorCurvesEnabled && this.colorCurves) {
  38293. defines += "#define COLORCURVES\r\n";
  38294. }
  38295. if (this._fromLinearSpace) {
  38296. defines += "#define FROMLINEARSPACE\r\n";
  38297. }
  38298. this.updateEffect(defines, null, samplers);
  38299. };
  38300. Object.defineProperty(ImageProcessingPostProcess, "VIGNETTEMODE_MULTIPLY", {
  38301. get: function () {
  38302. return ImageProcessingPostProcess._VIGNETTEMODE_MULTIPLY;
  38303. },
  38304. enumerable: true,
  38305. configurable: true
  38306. });
  38307. Object.defineProperty(ImageProcessingPostProcess, "VIGNETTEMODE_OPAQUE", {
  38308. get: function () {
  38309. return ImageProcessingPostProcess._VIGNETTEMODE_OPAQUE;
  38310. },
  38311. enumerable: true,
  38312. configurable: true
  38313. });
  38314. return ImageProcessingPostProcess;
  38315. }(BABYLON.PostProcess));
  38316. // Statics
  38317. ImageProcessingPostProcess._VIGNETTEMODE_MULTIPLY = 0;
  38318. ImageProcessingPostProcess._VIGNETTEMODE_OPAQUE = 1;
  38319. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  38320. })(BABYLON || (BABYLON = {}));
  38321. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  38322. var BABYLON;
  38323. (function (BABYLON) {
  38324. /**
  38325. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  38326. * It can help converting any input color in a desired output one. This can then be used to create effects
  38327. * from sepia, black and white to sixties or futuristic rendering...
  38328. *
  38329. * The only supported format is currently 3dl.
  38330. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  38331. */
  38332. var ColorGradingTexture = (function (_super) {
  38333. __extends(ColorGradingTexture, _super);
  38334. /**
  38335. * Instantiates a ColorGradingTexture from the following parameters.
  38336. *
  38337. * @param url The location of the color gradind data (currently only supporting 3dl)
  38338. * @param scene The scene the texture will be used in
  38339. */
  38340. function ColorGradingTexture(url, scene) {
  38341. var _this = _super.call(this, scene) || this;
  38342. if (!url) {
  38343. return _this;
  38344. }
  38345. _this._textureMatrix = BABYLON.Matrix.Identity();
  38346. _this.name = url;
  38347. _this.url = url;
  38348. _this.hasAlpha = false;
  38349. _this.isCube = false;
  38350. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38351. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38352. _this.anisotropicFilteringLevel = 1;
  38353. _this._texture = _this._getFromCache(url, true);
  38354. if (!_this._texture) {
  38355. if (!scene.useDelayedTextureLoading) {
  38356. _this.loadTexture();
  38357. }
  38358. else {
  38359. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  38360. }
  38361. }
  38362. return _this;
  38363. }
  38364. /**
  38365. * Returns the texture matrix used in most of the material.
  38366. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  38367. */
  38368. ColorGradingTexture.prototype.getTextureMatrix = function () {
  38369. return this._textureMatrix;
  38370. };
  38371. /**
  38372. * Occurs when the file being loaded is a .3dl LUT file.
  38373. */
  38374. ColorGradingTexture.prototype.load3dlTexture = function () {
  38375. var _this = this;
  38376. var mipLevels = 0;
  38377. var floatArrayView = null;
  38378. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38379. this._texture = texture;
  38380. var callback = function (text) {
  38381. var data;
  38382. var tempData;
  38383. var line;
  38384. var lines = text.split('\n');
  38385. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  38386. var maxColor = 0;
  38387. for (var i = 0; i < lines.length; i++) {
  38388. line = lines[i];
  38389. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  38390. continue;
  38391. if (line.indexOf('#') === 0)
  38392. continue;
  38393. var words = line.split(" ");
  38394. if (size === 0) {
  38395. // Number of space + one
  38396. size = words.length;
  38397. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  38398. tempData = new Float32Array(size * size * size * 4);
  38399. continue;
  38400. }
  38401. if (size != 0) {
  38402. var r = Math.max(parseInt(words[0]), 0);
  38403. var g = Math.max(parseInt(words[1]), 0);
  38404. var b = Math.max(parseInt(words[2]), 0);
  38405. maxColor = Math.max(r, maxColor);
  38406. maxColor = Math.max(g, maxColor);
  38407. maxColor = Math.max(b, maxColor);
  38408. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  38409. tempData[pixelStorageIndex + 0] = r;
  38410. tempData[pixelStorageIndex + 1] = g;
  38411. tempData[pixelStorageIndex + 2] = b;
  38412. tempData[pixelStorageIndex + 3] = 0;
  38413. pixelIndexSlice++;
  38414. if (pixelIndexSlice % size == 0) {
  38415. pixelIndexH++;
  38416. pixelIndexSlice = 0;
  38417. if (pixelIndexH % size == 0) {
  38418. pixelIndexW++;
  38419. pixelIndexH = 0;
  38420. }
  38421. }
  38422. }
  38423. }
  38424. for (var i = 0; i < tempData.length; i++) {
  38425. var value = tempData[i];
  38426. data[i] = (value / maxColor * 255);
  38427. }
  38428. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  38429. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38430. };
  38431. BABYLON.Tools.LoadFile(this.url, callback);
  38432. return this._texture;
  38433. };
  38434. /**
  38435. * Starts the loading process of the texture.
  38436. */
  38437. ColorGradingTexture.prototype.loadTexture = function () {
  38438. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  38439. this.load3dlTexture();
  38440. }
  38441. };
  38442. /**
  38443. * Clones the color gradind texture.
  38444. */
  38445. ColorGradingTexture.prototype.clone = function () {
  38446. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  38447. // Base texture
  38448. newTexture.level = this.level;
  38449. return newTexture;
  38450. };
  38451. /**
  38452. * Called during delayed load for textures.
  38453. */
  38454. ColorGradingTexture.prototype.delayLoad = function () {
  38455. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  38456. return;
  38457. }
  38458. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38459. this._texture = this._getFromCache(this.url, true);
  38460. if (!this._texture) {
  38461. this.loadTexture();
  38462. }
  38463. };
  38464. /**
  38465. * Binds the color grading to the shader.
  38466. * @param colorGrading The texture to bind
  38467. * @param effect The effect to bind to
  38468. */
  38469. ColorGradingTexture.Bind = function (colorGrading, effect) {
  38470. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  38471. var x = colorGrading.level; // Texture Level
  38472. var y = colorGrading.getSize().height; // Texture Size example with 8
  38473. var z = y - 1.0; // SizeMinusOne 8 - 1
  38474. var w = 1 / y; // Space of 1 slice 1 / 8
  38475. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  38476. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  38477. var slicePixelSizeV = w; // Space of 1 pixel in V direction, e.g. 1/8 // Space of 1 pixel in V direction, e.g. 1/8
  38478. var x2 = z * slicePixelSizeU; // Extent of lookup range in U for a single slice so that range corresponds to (size-1) texels, for example 7/64
  38479. var y2 = z / y; // Extent of lookup range in V for a single slice so that range corresponds to (size-1) texels, for example 7/8
  38480. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  38481. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  38482. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  38483. };
  38484. /**
  38485. * Prepare the list of uniforms associated with the ColorGrading effects.
  38486. * @param uniformsList The list of uniforms used in the effect
  38487. * @param samplersList The list of samplers used in the effect
  38488. */
  38489. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  38490. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  38491. samplersList.push("cameraColorGrading2DSampler");
  38492. };
  38493. /**
  38494. * Parses a color grading texture serialized by Babylon.
  38495. * @param parsedTexture The texture information being parsedTexture
  38496. * @param scene The scene to load the texture in
  38497. * @param rootUrl The root url of the data assets to load
  38498. * @return A color gradind texture
  38499. */
  38500. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  38501. var texture = null;
  38502. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  38503. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  38504. texture.name = parsedTexture.name;
  38505. texture.level = parsedTexture.level;
  38506. }
  38507. return texture;
  38508. };
  38509. /**
  38510. * Serializes the LUT texture to json format.
  38511. */
  38512. ColorGradingTexture.prototype.serialize = function () {
  38513. if (!this.name) {
  38514. return null;
  38515. }
  38516. var serializationObject = {};
  38517. serializationObject.name = this.name;
  38518. serializationObject.level = this.level;
  38519. serializationObject.customType = "BABYLON.ColorGradingTexture";
  38520. return serializationObject;
  38521. };
  38522. return ColorGradingTexture;
  38523. }(BABYLON.BaseTexture));
  38524. /**
  38525. * Empty line regex stored for GC.
  38526. */
  38527. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  38528. BABYLON.ColorGradingTexture = ColorGradingTexture;
  38529. })(BABYLON || (BABYLON = {}));
  38530. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  38531. var BABYLON;
  38532. (function (BABYLON) {
  38533. /**
  38534. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38535. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38536. * 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;
  38537. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38538. */
  38539. var ColorCurves = (function () {
  38540. function ColorCurves() {
  38541. this._dirty = true;
  38542. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  38543. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  38544. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38545. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  38546. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38547. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  38548. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  38549. this._globalHue = 30;
  38550. this._globalDensity = 0;
  38551. this._globalSaturation = 0;
  38552. this._globalExposure = 0;
  38553. this._highlightsHue = 30;
  38554. this._highlightsDensity = 0;
  38555. this._highlightsSaturation = 0;
  38556. this._highlightsExposure = 0;
  38557. this._midtonesHue = 30;
  38558. this._midtonesDensity = 0;
  38559. this._midtonesSaturation = 0;
  38560. this._midtonesExposure = 0;
  38561. this._shadowsHue = 30;
  38562. this._shadowsDensity = 0;
  38563. this._shadowsSaturation = 0;
  38564. this._shadowsExposure = 0;
  38565. }
  38566. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  38567. /**
  38568. * Gets the global Hue value.
  38569. * 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).
  38570. */
  38571. get: function () {
  38572. return this._globalHue;
  38573. },
  38574. /**
  38575. * Sets the global Hue value.
  38576. * 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).
  38577. */
  38578. set: function (value) {
  38579. this._globalHue = value;
  38580. this._dirty = true;
  38581. },
  38582. enumerable: true,
  38583. configurable: true
  38584. });
  38585. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  38586. /**
  38587. * Gets the global Density value.
  38588. * 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.
  38589. * Values less than zero provide a filter of opposite hue.
  38590. */
  38591. get: function () {
  38592. return this._globalDensity;
  38593. },
  38594. /**
  38595. * Sets the global Density value.
  38596. * 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.
  38597. * Values less than zero provide a filter of opposite hue.
  38598. */
  38599. set: function (value) {
  38600. this._globalDensity = value;
  38601. this._dirty = true;
  38602. },
  38603. enumerable: true,
  38604. configurable: true
  38605. });
  38606. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  38607. /**
  38608. * Gets the global Saturation value.
  38609. * 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.
  38610. */
  38611. get: function () {
  38612. return this._globalSaturation;
  38613. },
  38614. /**
  38615. * Sets the global Saturation value.
  38616. * 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.
  38617. */
  38618. set: function (value) {
  38619. this._globalSaturation = value;
  38620. this._dirty = true;
  38621. },
  38622. enumerable: true,
  38623. configurable: true
  38624. });
  38625. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  38626. /**
  38627. * Gets the highlights Hue value.
  38628. * 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).
  38629. */
  38630. get: function () {
  38631. return this._highlightsHue;
  38632. },
  38633. /**
  38634. * Sets the highlights Hue value.
  38635. * 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).
  38636. */
  38637. set: function (value) {
  38638. this._highlightsHue = value;
  38639. this._dirty = true;
  38640. },
  38641. enumerable: true,
  38642. configurable: true
  38643. });
  38644. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  38645. /**
  38646. * Gets the highlights Density value.
  38647. * 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.
  38648. * Values less than zero provide a filter of opposite hue.
  38649. */
  38650. get: function () {
  38651. return this._highlightsDensity;
  38652. },
  38653. /**
  38654. * Sets the highlights Density value.
  38655. * 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.
  38656. * Values less than zero provide a filter of opposite hue.
  38657. */
  38658. set: function (value) {
  38659. this._highlightsDensity = value;
  38660. this._dirty = true;
  38661. },
  38662. enumerable: true,
  38663. configurable: true
  38664. });
  38665. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  38666. /**
  38667. * Gets the highlights Saturation value.
  38668. * 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.
  38669. */
  38670. get: function () {
  38671. return this._highlightsSaturation;
  38672. },
  38673. /**
  38674. * Sets the highlights Saturation value.
  38675. * 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.
  38676. */
  38677. set: function (value) {
  38678. this._highlightsSaturation = value;
  38679. this._dirty = true;
  38680. },
  38681. enumerable: true,
  38682. configurable: true
  38683. });
  38684. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  38685. /**
  38686. * Gets the highlights Exposure value.
  38687. * 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.
  38688. */
  38689. get: function () {
  38690. return this._highlightsExposure;
  38691. },
  38692. /**
  38693. * Sets the highlights Exposure value.
  38694. * 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.
  38695. */
  38696. set: function (value) {
  38697. this._highlightsExposure = value;
  38698. this._dirty = true;
  38699. },
  38700. enumerable: true,
  38701. configurable: true
  38702. });
  38703. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  38704. /**
  38705. * Gets the midtones Hue value.
  38706. * 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).
  38707. */
  38708. get: function () {
  38709. return this._midtonesHue;
  38710. },
  38711. /**
  38712. * Sets the midtones Hue value.
  38713. * 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).
  38714. */
  38715. set: function (value) {
  38716. this._midtonesHue = value;
  38717. this._dirty = true;
  38718. },
  38719. enumerable: true,
  38720. configurable: true
  38721. });
  38722. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  38723. /**
  38724. * Gets the midtones Density value.
  38725. * 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.
  38726. * Values less than zero provide a filter of opposite hue.
  38727. */
  38728. get: function () {
  38729. return this._midtonesDensity;
  38730. },
  38731. /**
  38732. * Sets the midtones Density value.
  38733. * 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.
  38734. * Values less than zero provide a filter of opposite hue.
  38735. */
  38736. set: function (value) {
  38737. this._midtonesDensity = value;
  38738. this._dirty = true;
  38739. },
  38740. enumerable: true,
  38741. configurable: true
  38742. });
  38743. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  38744. /**
  38745. * Gets the midtones Saturation value.
  38746. * 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.
  38747. */
  38748. get: function () {
  38749. return this._midtonesSaturation;
  38750. },
  38751. /**
  38752. * Sets the midtones Saturation value.
  38753. * 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.
  38754. */
  38755. set: function (value) {
  38756. this._midtonesSaturation = value;
  38757. this._dirty = true;
  38758. },
  38759. enumerable: true,
  38760. configurable: true
  38761. });
  38762. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  38763. /**
  38764. * Gets the midtones Exposure value.
  38765. * 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.
  38766. */
  38767. get: function () {
  38768. return this._midtonesExposure;
  38769. },
  38770. /**
  38771. * Sets the midtones Exposure value.
  38772. * 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.
  38773. */
  38774. set: function (value) {
  38775. this._midtonesExposure = value;
  38776. this._dirty = true;
  38777. },
  38778. enumerable: true,
  38779. configurable: true
  38780. });
  38781. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  38782. /**
  38783. * Gets the shadows Hue value.
  38784. * 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).
  38785. */
  38786. get: function () {
  38787. return this._shadowsHue;
  38788. },
  38789. /**
  38790. * Sets the shadows Hue value.
  38791. * 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).
  38792. */
  38793. set: function (value) {
  38794. this._shadowsHue = value;
  38795. this._dirty = true;
  38796. },
  38797. enumerable: true,
  38798. configurable: true
  38799. });
  38800. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  38801. /**
  38802. * Gets the shadows Density value.
  38803. * 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.
  38804. * Values less than zero provide a filter of opposite hue.
  38805. */
  38806. get: function () {
  38807. return this._shadowsDensity;
  38808. },
  38809. /**
  38810. * Sets the shadows Density value.
  38811. * 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.
  38812. * Values less than zero provide a filter of opposite hue.
  38813. */
  38814. set: function (value) {
  38815. this._shadowsDensity = value;
  38816. this._dirty = true;
  38817. },
  38818. enumerable: true,
  38819. configurable: true
  38820. });
  38821. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  38822. /**
  38823. * Gets the shadows Saturation value.
  38824. * 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.
  38825. */
  38826. get: function () {
  38827. return this._shadowsSaturation;
  38828. },
  38829. /**
  38830. * Sets the shadows Saturation value.
  38831. * 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.
  38832. */
  38833. set: function (value) {
  38834. this._shadowsSaturation = value;
  38835. this._dirty = true;
  38836. },
  38837. enumerable: true,
  38838. configurable: true
  38839. });
  38840. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  38841. /**
  38842. * Gets the shadows Exposure value.
  38843. * 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.
  38844. */
  38845. get: function () {
  38846. return this._shadowsExposure;
  38847. },
  38848. /**
  38849. * Sets the shadows Exposure value.
  38850. * 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.
  38851. */
  38852. set: function (value) {
  38853. this._shadowsExposure = value;
  38854. this._dirty = true;
  38855. },
  38856. enumerable: true,
  38857. configurable: true
  38858. });
  38859. /**
  38860. * Binds the color curves to the shader.
  38861. * @param colorCurves The color curve to bind
  38862. * @param effect The effect to bind to
  38863. */
  38864. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  38865. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  38866. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  38867. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  38868. if (colorCurves._dirty) {
  38869. colorCurves._dirty = false;
  38870. // Fill in global info.
  38871. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  38872. // Compute highlights info.
  38873. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  38874. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  38875. // Compute midtones info.
  38876. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  38877. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  38878. // Compute shadows info.
  38879. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  38880. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  38881. // Compute deltas (neutral is midtones).
  38882. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  38883. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  38884. }
  38885. if (effect) {
  38886. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  38887. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  38888. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  38889. }
  38890. };
  38891. /**
  38892. * Prepare the list of uniforms associated with the ColorCurves effects.
  38893. * @param uniformsList The list of uniforms used in the effect
  38894. */
  38895. ColorCurves.PrepareUniforms = function (uniformsList) {
  38896. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  38897. };
  38898. /**
  38899. * Returns color grading data based on a hue, density, saturation and exposure value.
  38900. * @param filterHue The hue of the color filter.
  38901. * @param filterDensity The density of the color filter.
  38902. * @param saturation The saturation.
  38903. * @param exposure The exposure.
  38904. * @param result The result data container.
  38905. */
  38906. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  38907. if (hue == null) {
  38908. return;
  38909. }
  38910. hue = ColorCurves.clamp(hue, 0, 360);
  38911. density = ColorCurves.clamp(density, -100, 100);
  38912. saturation = ColorCurves.clamp(saturation, -100, 100);
  38913. exposure = ColorCurves.clamp(exposure, -100, 100);
  38914. // Remap the slider/config filter density with non-linear mapping and also scale by half
  38915. // so that the maximum filter density is only 50% control. This provides fine control
  38916. // for small values and reasonable range.
  38917. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  38918. density *= 0.5;
  38919. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  38920. if (density < 0) {
  38921. density *= -1;
  38922. hue = (hue + 180) % 360;
  38923. }
  38924. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  38925. result.scaleToRef(2, result);
  38926. result.a = 1 + 0.01 * saturation;
  38927. };
  38928. /**
  38929. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  38930. * @param value The input slider value in range [-100,100].
  38931. * @returns Adjusted value.
  38932. */
  38933. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  38934. value /= 100;
  38935. var x = Math.abs(value);
  38936. x = Math.pow(x, 2);
  38937. if (value < 0) {
  38938. x *= -1;
  38939. }
  38940. x *= 100;
  38941. return x;
  38942. };
  38943. /**
  38944. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  38945. * @param hue The hue (H) input.
  38946. * @param saturation The saturation (S) input.
  38947. * @param brightness The brightness (B) input.
  38948. * @result An RGBA color represented as Vector4.
  38949. */
  38950. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38951. var h = ColorCurves.clamp(hue, 0, 360);
  38952. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38953. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38954. if (s === 0) {
  38955. result.r = v;
  38956. result.g = v;
  38957. result.b = v;
  38958. }
  38959. else {
  38960. // sector 0 to 5
  38961. h /= 60;
  38962. var i = Math.floor(h);
  38963. // fractional part of h
  38964. var f = h - i;
  38965. var p = v * (1 - s);
  38966. var q = v * (1 - s * f);
  38967. var t = v * (1 - s * (1 - f));
  38968. switch (i) {
  38969. case 0:
  38970. result.r = v;
  38971. result.g = t;
  38972. result.b = p;
  38973. break;
  38974. case 1:
  38975. result.r = q;
  38976. result.g = v;
  38977. result.b = p;
  38978. break;
  38979. case 2:
  38980. result.r = p;
  38981. result.g = v;
  38982. result.b = t;
  38983. break;
  38984. case 3:
  38985. result.r = p;
  38986. result.g = q;
  38987. result.b = v;
  38988. break;
  38989. case 4:
  38990. result.r = t;
  38991. result.g = p;
  38992. result.b = v;
  38993. break;
  38994. default:
  38995. result.r = v;
  38996. result.g = p;
  38997. result.b = q;
  38998. break;
  38999. }
  39000. }
  39001. result.a = 1;
  39002. };
  39003. /**
  39004. * Returns a value clamped between min and max
  39005. * @param value The value to clamp
  39006. * @param min The minimum of value
  39007. * @param max The maximum of value
  39008. * @returns The clamped value.
  39009. */
  39010. ColorCurves.clamp = function (value, min, max) {
  39011. return Math.min(Math.max(value, min), max);
  39012. };
  39013. /**
  39014. * Clones the current color curve instance.
  39015. * @return The cloned curves
  39016. */
  39017. ColorCurves.prototype.clone = function () {
  39018. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  39019. };
  39020. /**
  39021. * Serializes the current color curve instance to a json representation.
  39022. * @return a JSON representation
  39023. */
  39024. ColorCurves.prototype.serialize = function () {
  39025. return BABYLON.SerializationHelper.Serialize(this);
  39026. };
  39027. /**
  39028. * Parses the color curve from a json representation.
  39029. * @param source the JSON source to parse
  39030. * @return The parsed curves
  39031. */
  39032. ColorCurves.Parse = function (source) {
  39033. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  39034. };
  39035. return ColorCurves;
  39036. }());
  39037. __decorate([
  39038. BABYLON.serialize()
  39039. ], ColorCurves.prototype, "_globalHue", void 0);
  39040. __decorate([
  39041. BABYLON.serialize()
  39042. ], ColorCurves.prototype, "_globalDensity", void 0);
  39043. __decorate([
  39044. BABYLON.serialize()
  39045. ], ColorCurves.prototype, "_globalSaturation", void 0);
  39046. __decorate([
  39047. BABYLON.serialize()
  39048. ], ColorCurves.prototype, "_globalExposure", void 0);
  39049. __decorate([
  39050. BABYLON.serialize()
  39051. ], ColorCurves.prototype, "_highlightsHue", void 0);
  39052. __decorate([
  39053. BABYLON.serialize()
  39054. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  39055. __decorate([
  39056. BABYLON.serialize()
  39057. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  39058. __decorate([
  39059. BABYLON.serialize()
  39060. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  39061. __decorate([
  39062. BABYLON.serialize()
  39063. ], ColorCurves.prototype, "_midtonesHue", void 0);
  39064. __decorate([
  39065. BABYLON.serialize()
  39066. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  39067. __decorate([
  39068. BABYLON.serialize()
  39069. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  39070. __decorate([
  39071. BABYLON.serialize()
  39072. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  39073. BABYLON.ColorCurves = ColorCurves;
  39074. })(BABYLON || (BABYLON = {}));
  39075. //# sourceMappingURL=babylon.colorCurves.js.map
  39076. var BABYLON;
  39077. (function (BABYLON) {
  39078. var PostProcessRenderPipelineManager = (function () {
  39079. function PostProcessRenderPipelineManager() {
  39080. this._renderPipelines = {};
  39081. }
  39082. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  39083. this._renderPipelines[renderPipeline._name] = renderPipeline;
  39084. };
  39085. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  39086. var renderPipeline = this._renderPipelines[renderPipelineName];
  39087. if (!renderPipeline) {
  39088. return;
  39089. }
  39090. renderPipeline._attachCameras(cameras, unique);
  39091. };
  39092. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  39093. var renderPipeline = this._renderPipelines[renderPipelineName];
  39094. if (!renderPipeline) {
  39095. return;
  39096. }
  39097. renderPipeline._detachCameras(cameras);
  39098. };
  39099. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  39100. var renderPipeline = this._renderPipelines[renderPipelineName];
  39101. if (!renderPipeline) {
  39102. return;
  39103. }
  39104. renderPipeline._enableEffect(renderEffectName, cameras);
  39105. };
  39106. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  39107. var renderPipeline = this._renderPipelines[renderPipelineName];
  39108. if (!renderPipeline) {
  39109. return;
  39110. }
  39111. renderPipeline._disableEffect(renderEffectName, cameras);
  39112. };
  39113. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  39114. var renderPipeline = this._renderPipelines[renderPipelineName];
  39115. if (!renderPipeline) {
  39116. return;
  39117. }
  39118. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  39119. };
  39120. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  39121. var renderPipeline = this._renderPipelines[renderPipelineName];
  39122. if (!renderPipeline) {
  39123. return;
  39124. }
  39125. renderPipeline._disableDisplayOnlyPass(cameras);
  39126. };
  39127. PostProcessRenderPipelineManager.prototype.update = function () {
  39128. for (var renderPipelineName in this._renderPipelines) {
  39129. var pipeline = this._renderPipelines[renderPipelineName];
  39130. if (!pipeline.isSupported) {
  39131. pipeline.dispose();
  39132. delete this._renderPipelines[renderPipelineName];
  39133. }
  39134. else {
  39135. pipeline._update();
  39136. }
  39137. }
  39138. };
  39139. return PostProcessRenderPipelineManager;
  39140. }());
  39141. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  39142. })(BABYLON || (BABYLON = {}));
  39143. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  39144. var BABYLON;
  39145. (function (BABYLON) {
  39146. var PostProcessRenderPass = (function () {
  39147. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  39148. this._enabled = true;
  39149. this._refCount = 0;
  39150. this._name = name;
  39151. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  39152. this.setRenderList(renderList);
  39153. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  39154. this._renderTexture.onAfterRenderObservable.add(afterRender);
  39155. this._scene = scene;
  39156. this._renderList = renderList;
  39157. }
  39158. // private
  39159. PostProcessRenderPass.prototype._incRefCount = function () {
  39160. if (this._refCount === 0) {
  39161. this._scene.customRenderTargets.push(this._renderTexture);
  39162. }
  39163. return ++this._refCount;
  39164. };
  39165. PostProcessRenderPass.prototype._decRefCount = function () {
  39166. this._refCount--;
  39167. if (this._refCount <= 0) {
  39168. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  39169. }
  39170. return this._refCount;
  39171. };
  39172. PostProcessRenderPass.prototype._update = function () {
  39173. this.setRenderList(this._renderList);
  39174. };
  39175. // public
  39176. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  39177. this._renderTexture.renderList = renderList;
  39178. };
  39179. PostProcessRenderPass.prototype.getRenderTexture = function () {
  39180. return this._renderTexture;
  39181. };
  39182. return PostProcessRenderPass;
  39183. }());
  39184. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  39185. })(BABYLON || (BABYLON = {}));
  39186. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  39187. var BABYLON;
  39188. (function (BABYLON) {
  39189. var PostProcessRenderEffect = (function () {
  39190. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  39191. this._engine = engine;
  39192. this._name = name;
  39193. this._singleInstance = singleInstance || true;
  39194. this._getPostProcess = getPostProcess;
  39195. this._cameras = [];
  39196. this._indicesForCamera = [];
  39197. this._postProcesses = {};
  39198. this._renderPasses = {};
  39199. this._renderEffectAsPasses = {};
  39200. }
  39201. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  39202. get: function () {
  39203. for (var index in this._postProcesses) {
  39204. if (!this._postProcesses[index].isSupported) {
  39205. return false;
  39206. }
  39207. }
  39208. return true;
  39209. },
  39210. enumerable: true,
  39211. configurable: true
  39212. });
  39213. PostProcessRenderEffect.prototype._update = function () {
  39214. for (var renderPassName in this._renderPasses) {
  39215. this._renderPasses[renderPassName]._update();
  39216. }
  39217. };
  39218. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  39219. this._renderPasses[renderPass._name] = renderPass;
  39220. this._linkParameters();
  39221. };
  39222. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  39223. delete this._renderPasses[renderPass._name];
  39224. this._linkParameters();
  39225. };
  39226. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  39227. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  39228. this._linkParameters();
  39229. };
  39230. PostProcessRenderEffect.prototype.getPass = function (passName) {
  39231. for (var renderPassName in this._renderPasses) {
  39232. if (renderPassName === passName) {
  39233. return this._renderPasses[passName];
  39234. }
  39235. }
  39236. };
  39237. PostProcessRenderEffect.prototype.emptyPasses = function () {
  39238. this._renderPasses = {};
  39239. this._linkParameters();
  39240. };
  39241. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  39242. var cameraKey;
  39243. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39244. for (var i = 0; i < _cam.length; i++) {
  39245. var camera = _cam[i];
  39246. var cameraName = camera.name;
  39247. if (this._singleInstance) {
  39248. cameraKey = 0;
  39249. }
  39250. else {
  39251. cameraKey = cameraName;
  39252. }
  39253. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  39254. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  39255. if (!this._indicesForCamera[cameraName]) {
  39256. this._indicesForCamera[cameraName] = [];
  39257. }
  39258. this._indicesForCamera[cameraName].push(index);
  39259. if (this._cameras.indexOf(camera) === -1) {
  39260. this._cameras[cameraName] = camera;
  39261. }
  39262. for (var passName in this._renderPasses) {
  39263. this._renderPasses[passName]._incRefCount();
  39264. }
  39265. }
  39266. this._linkParameters();
  39267. };
  39268. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  39269. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39270. for (var i = 0; i < _cam.length; i++) {
  39271. var camera = _cam[i];
  39272. var cameraName = camera.name;
  39273. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  39274. var index = this._cameras.indexOf(cameraName);
  39275. this._indicesForCamera.splice(index, 1);
  39276. this._cameras.splice(index, 1);
  39277. for (var passName in this._renderPasses) {
  39278. this._renderPasses[passName]._decRefCount();
  39279. }
  39280. }
  39281. };
  39282. PostProcessRenderEffect.prototype._enable = function (cameras) {
  39283. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39284. for (var i = 0; i < _cam.length; i++) {
  39285. var camera = _cam[i];
  39286. var cameraName = camera.name;
  39287. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  39288. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  39289. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  39290. }
  39291. }
  39292. for (var passName in this._renderPasses) {
  39293. this._renderPasses[passName]._incRefCount();
  39294. }
  39295. }
  39296. };
  39297. PostProcessRenderEffect.prototype._disable = function (cameras) {
  39298. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39299. for (var i = 0; i < _cam.length; i++) {
  39300. var camera = _cam[i];
  39301. var cameraName = camera.Name;
  39302. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  39303. for (var passName in this._renderPasses) {
  39304. this._renderPasses[passName]._decRefCount();
  39305. }
  39306. }
  39307. };
  39308. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  39309. if (this._singleInstance) {
  39310. return this._postProcesses[0];
  39311. }
  39312. else {
  39313. return this._postProcesses[camera.name];
  39314. }
  39315. };
  39316. PostProcessRenderEffect.prototype._linkParameters = function () {
  39317. var _this = this;
  39318. for (var index in this._postProcesses) {
  39319. if (this.applyParameters) {
  39320. this.applyParameters(this._postProcesses[index]);
  39321. }
  39322. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  39323. _this._linkTextures(effect);
  39324. });
  39325. }
  39326. };
  39327. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  39328. for (var renderPassName in this._renderPasses) {
  39329. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  39330. }
  39331. for (var renderEffectName in this._renderEffectAsPasses) {
  39332. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  39333. }
  39334. };
  39335. return PostProcessRenderEffect;
  39336. }());
  39337. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  39338. })(BABYLON || (BABYLON = {}));
  39339. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  39340. var BABYLON;
  39341. (function (BABYLON) {
  39342. var PostProcessRenderPipeline = (function () {
  39343. function PostProcessRenderPipeline(engine, name) {
  39344. this._engine = engine;
  39345. this._name = name;
  39346. this._renderEffects = new Array();
  39347. this._renderEffectsForIsolatedPass = new Array();
  39348. this._cameras = [];
  39349. }
  39350. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  39351. get: function () {
  39352. for (var renderEffectName in this._renderEffects) {
  39353. if (!this._renderEffects[renderEffectName].isSupported) {
  39354. return false;
  39355. }
  39356. }
  39357. return true;
  39358. },
  39359. enumerable: true,
  39360. configurable: true
  39361. });
  39362. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  39363. this._renderEffects[renderEffect._name] = renderEffect;
  39364. };
  39365. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  39366. var renderEffects = this._renderEffects[renderEffectName];
  39367. if (!renderEffects) {
  39368. return;
  39369. }
  39370. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  39371. };
  39372. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  39373. var renderEffects = this._renderEffects[renderEffectName];
  39374. if (!renderEffects) {
  39375. return;
  39376. }
  39377. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  39378. };
  39379. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  39380. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39381. var indicesToDelete = [];
  39382. var i;
  39383. for (i = 0; i < _cam.length; i++) {
  39384. var camera = _cam[i];
  39385. var cameraName = camera.name;
  39386. if (this._cameras.indexOf(camera) === -1) {
  39387. this._cameras[cameraName] = camera;
  39388. }
  39389. else if (unique) {
  39390. indicesToDelete.push(i);
  39391. }
  39392. }
  39393. for (i = 0; i < indicesToDelete.length; i++) {
  39394. cameras.splice(indicesToDelete[i], 1);
  39395. }
  39396. for (var renderEffectName in this._renderEffects) {
  39397. this._renderEffects[renderEffectName]._attachCameras(_cam);
  39398. }
  39399. };
  39400. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  39401. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39402. for (var renderEffectName in this._renderEffects) {
  39403. this._renderEffects[renderEffectName]._detachCameras(_cam);
  39404. }
  39405. for (var i = 0; i < _cam.length; i++) {
  39406. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  39407. }
  39408. };
  39409. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  39410. var _this = this;
  39411. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39412. var pass = null;
  39413. var renderEffectName;
  39414. for (renderEffectName in this._renderEffects) {
  39415. pass = this._renderEffects[renderEffectName].getPass(passName);
  39416. if (pass != null) {
  39417. break;
  39418. }
  39419. }
  39420. if (pass === null) {
  39421. return;
  39422. }
  39423. for (renderEffectName in this._renderEffects) {
  39424. this._renderEffects[renderEffectName]._disable(_cam);
  39425. }
  39426. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  39427. for (var i = 0; i < _cam.length; i++) {
  39428. var camera = _cam[i];
  39429. var cameraName = camera.name;
  39430. 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); });
  39431. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  39432. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  39433. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  39434. }
  39435. };
  39436. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  39437. var _this = this;
  39438. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  39439. for (var i = 0; i < _cam.length; i++) {
  39440. var camera = _cam[i];
  39441. var cameraName = camera.name;
  39442. 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); });
  39443. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  39444. }
  39445. for (var renderEffectName in this._renderEffects) {
  39446. this._renderEffects[renderEffectName]._enable(_cam);
  39447. }
  39448. };
  39449. PostProcessRenderPipeline.prototype._update = function () {
  39450. for (var renderEffectName in this._renderEffects) {
  39451. this._renderEffects[renderEffectName]._update();
  39452. }
  39453. for (var i = 0; i < this._cameras.length; i++) {
  39454. var cameraName = this._cameras[i].name;
  39455. if (this._renderEffectsForIsolatedPass[cameraName]) {
  39456. this._renderEffectsForIsolatedPass[cameraName]._update();
  39457. }
  39458. }
  39459. };
  39460. PostProcessRenderPipeline.prototype._reset = function () {
  39461. this._renderEffects = new Array();
  39462. this._renderEffectsForIsolatedPass = new Array();
  39463. };
  39464. PostProcessRenderPipeline.prototype.dispose = function () {
  39465. // Must be implemented by children
  39466. };
  39467. return PostProcessRenderPipeline;
  39468. }());
  39469. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  39470. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  39471. __decorate([
  39472. BABYLON.serialize()
  39473. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  39474. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  39475. })(BABYLON || (BABYLON = {}));
  39476. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  39477. var BABYLON;
  39478. (function (BABYLON) {
  39479. var DefaultRenderingPipeline = (function (_super) {
  39480. __extends(DefaultRenderingPipeline, _super);
  39481. /**
  39482. * @constructor
  39483. * @param {string} name - The rendering pipeline name
  39484. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  39485. * @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)
  39486. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  39487. */
  39488. function DefaultRenderingPipeline(name, hdr, scene, cameras) {
  39489. var _this = _super.call(this, scene.getEngine(), name) || this;
  39490. _this.PassPostProcessId = "PassPostProcessEffect";
  39491. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  39492. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  39493. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  39494. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  39495. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  39496. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  39497. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  39498. // IAnimatable
  39499. _this.animations = [];
  39500. // Values
  39501. _this._bloomEnabled = false;
  39502. _this._fxaaEnabled = false;
  39503. _this._imageProcessingEnabled = true;
  39504. _this._bloomScale = 0.6;
  39505. /**
  39506. * Specifies the size of the bloom blur kernel, relative to the final output size
  39507. */
  39508. _this.bloomKernel = 64;
  39509. /**
  39510. * Specifies the weight of the bloom in the final rendering
  39511. */
  39512. _this._bloomWeight = 0.15;
  39513. _this._cameras = cameras || [];
  39514. // Initialize
  39515. _this._hdr = hdr;
  39516. _this._scene = scene;
  39517. // Misc
  39518. _this._defaultPipelineTextureType = !hdr ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : (scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  39519. // Attach
  39520. scene.postProcessRenderPipelineManager.addPipeline(_this);
  39521. _this._buildPipeline();
  39522. return _this;
  39523. }
  39524. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  39525. get: function () {
  39526. return this._bloomWeight;
  39527. },
  39528. set: function (value) {
  39529. if (this._bloomWeight === value) {
  39530. return;
  39531. }
  39532. this._bloomWeight = value;
  39533. if (this._hdr && this.copyBack) {
  39534. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  39535. }
  39536. },
  39537. enumerable: true,
  39538. configurable: true
  39539. });
  39540. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  39541. get: function () {
  39542. return this._bloomScale;
  39543. },
  39544. set: function (value) {
  39545. if (this._bloomScale === value) {
  39546. return;
  39547. }
  39548. this._bloomScale = value;
  39549. this._buildPipeline();
  39550. },
  39551. enumerable: true,
  39552. configurable: true
  39553. });
  39554. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  39555. get: function () {
  39556. return this._bloomEnabled;
  39557. },
  39558. set: function (enabled) {
  39559. if (this._bloomEnabled === enabled) {
  39560. return;
  39561. }
  39562. this._bloomEnabled = enabled;
  39563. this._buildPipeline();
  39564. },
  39565. enumerable: true,
  39566. configurable: true
  39567. });
  39568. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  39569. get: function () {
  39570. return this._fxaaEnabled;
  39571. },
  39572. set: function (enabled) {
  39573. if (this._fxaaEnabled === enabled) {
  39574. return;
  39575. }
  39576. this._fxaaEnabled = enabled;
  39577. this._buildPipeline();
  39578. },
  39579. enumerable: true,
  39580. configurable: true
  39581. });
  39582. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  39583. get: function () {
  39584. return this._imageProcessingEnabled;
  39585. },
  39586. set: function (enabled) {
  39587. if (this._imageProcessingEnabled === enabled) {
  39588. return;
  39589. }
  39590. this._imageProcessingEnabled = enabled;
  39591. this._buildPipeline();
  39592. },
  39593. enumerable: true,
  39594. configurable: true
  39595. });
  39596. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  39597. var _this = this;
  39598. var engine = this._scene.getEngine();
  39599. this._disposePostProcesses();
  39600. this._reset();
  39601. if (this.bloomEnabled) {
  39602. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  39603. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  39604. if (!this._hdr) {
  39605. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  39606. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  39607. this.highlights.autoClear = false;
  39608. this.highlights.alwaysForcePOT = true;
  39609. }
  39610. 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);
  39611. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  39612. this.blurX.alwaysForcePOT = true;
  39613. this.blurX.autoClear = false;
  39614. this.blurX.onActivateObservable.add(function () {
  39615. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  39616. _this.blurX.kernel = _this.bloomKernel * dw;
  39617. });
  39618. 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);
  39619. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  39620. this.blurY.alwaysForcePOT = true;
  39621. this.blurY.autoClear = false;
  39622. this.blurY.onActivateObservable.add(function () {
  39623. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  39624. _this.blurY.kernel = _this.bloomKernel * dh;
  39625. });
  39626. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  39627. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  39628. this.copyBack.alwaysForcePOT = true;
  39629. if (this._hdr) {
  39630. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  39631. var w = this.bloomWeight;
  39632. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  39633. }
  39634. else {
  39635. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  39636. }
  39637. this.copyBack.autoClear = false;
  39638. }
  39639. if (this._imageProcessingEnabled) {
  39640. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  39641. if (this._hdr) {
  39642. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  39643. }
  39644. }
  39645. if (this.fxaaEnabled) {
  39646. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  39647. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  39648. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  39649. }
  39650. else {
  39651. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  39652. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  39653. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  39654. }
  39655. if (this.bloomEnabled) {
  39656. if (this._hdr) {
  39657. this.copyBack.shareOutputWith(this.blurX);
  39658. if (this.imageProcessing) {
  39659. this.imageProcessing.shareOutputWith(this.pass);
  39660. this.imageProcessing.autoClear = false;
  39661. }
  39662. else if (this.fxaa) {
  39663. this.fxaa.shareOutputWith(this.pass);
  39664. }
  39665. else {
  39666. this.finalMerge.shareOutputWith(this.pass);
  39667. }
  39668. }
  39669. else {
  39670. if (this.fxaa) {
  39671. this.fxaa.shareOutputWith(this.pass);
  39672. }
  39673. else {
  39674. this.finalMerge.shareOutputWith(this.pass);
  39675. }
  39676. }
  39677. }
  39678. if (this._cameras !== null) {
  39679. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  39680. }
  39681. };
  39682. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  39683. for (var i = 0; i < this._cameras.length; i++) {
  39684. var camera = this._cameras[i];
  39685. if (this.pass) {
  39686. this.pass.dispose(camera);
  39687. this.pass = null;
  39688. }
  39689. if (this.highlights) {
  39690. this.highlights.dispose(camera);
  39691. this.highlights = null;
  39692. }
  39693. if (this.blurX) {
  39694. this.blurX.dispose(camera);
  39695. this.blurX = null;
  39696. }
  39697. if (this.blurY) {
  39698. this.blurY.dispose(camera);
  39699. this.blurY = null;
  39700. }
  39701. if (this.copyBack) {
  39702. this.copyBack.dispose(camera);
  39703. this.copyBack = null;
  39704. }
  39705. if (this.imageProcessing) {
  39706. this.imageProcessing.dispose(camera);
  39707. this.imageProcessing = null;
  39708. }
  39709. if (this.fxaa) {
  39710. this.fxaa.dispose(camera);
  39711. this.fxaa = null;
  39712. }
  39713. if (this.finalMerge) {
  39714. this.finalMerge.dispose(camera);
  39715. this.finalMerge = null;
  39716. }
  39717. }
  39718. };
  39719. // Dispose
  39720. DefaultRenderingPipeline.prototype.dispose = function () {
  39721. this._disposePostProcesses();
  39722. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  39723. _super.prototype.dispose.call(this);
  39724. };
  39725. // Serialize rendering pipeline
  39726. DefaultRenderingPipeline.prototype.serialize = function () {
  39727. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39728. serializationObject.customType = "DefaultRenderingPipeline";
  39729. return serializationObject;
  39730. };
  39731. // Parse serialized pipeline
  39732. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  39733. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  39734. };
  39735. return DefaultRenderingPipeline;
  39736. }(BABYLON.PostProcessRenderPipeline));
  39737. __decorate([
  39738. BABYLON.serialize()
  39739. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  39740. __decorate([
  39741. BABYLON.serialize()
  39742. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  39743. __decorate([
  39744. BABYLON.serialize()
  39745. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  39746. __decorate([
  39747. BABYLON.serialize()
  39748. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  39749. __decorate([
  39750. BABYLON.serialize()
  39751. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  39752. __decorate([
  39753. BABYLON.serialize()
  39754. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  39755. __decorate([
  39756. BABYLON.serialize()
  39757. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  39758. __decorate([
  39759. BABYLON.serialize()
  39760. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  39761. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  39762. })(BABYLON || (BABYLON = {}));
  39763. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  39764. /// <reference path="babylon.mesh.ts" />
  39765. var BABYLON;
  39766. (function (BABYLON) {
  39767. var GroundMesh = (function (_super) {
  39768. __extends(GroundMesh, _super);
  39769. function GroundMesh(name, scene) {
  39770. var _this = _super.call(this, name, scene) || this;
  39771. _this.generateOctree = false;
  39772. _this._worldInverse = new BABYLON.Matrix();
  39773. return _this;
  39774. }
  39775. GroundMesh.prototype.getClassName = function () {
  39776. return "GroundMesh";
  39777. };
  39778. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  39779. get: function () {
  39780. return Math.min(this._subdivisionsX, this._subdivisionsY);
  39781. },
  39782. enumerable: true,
  39783. configurable: true
  39784. });
  39785. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  39786. get: function () {
  39787. return this._subdivisionsX;
  39788. },
  39789. enumerable: true,
  39790. configurable: true
  39791. });
  39792. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  39793. get: function () {
  39794. return this._subdivisionsY;
  39795. },
  39796. enumerable: true,
  39797. configurable: true
  39798. });
  39799. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  39800. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  39801. this._subdivisionsX = chunksCount;
  39802. this._subdivisionsY = chunksCount;
  39803. this.subdivide(chunksCount);
  39804. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  39805. };
  39806. /**
  39807. * Returns a height (y) value in the Worl system :
  39808. * the ground altitude at the coordinates (x, z) expressed in the World system.
  39809. * Returns the ground y position if (x, z) are outside the ground surface.
  39810. */
  39811. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  39812. var world = this.getWorldMatrix();
  39813. var invMat = BABYLON.Tmp.Matrix[5];
  39814. world.invertToRef(invMat);
  39815. var tmpVect = BABYLON.Tmp.Vector3[8];
  39816. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  39817. x = tmpVect.x;
  39818. z = tmpVect.z;
  39819. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  39820. return this.position.y;
  39821. }
  39822. if (!this._heightQuads || this._heightQuads.length == 0) {
  39823. this._initHeightQuads();
  39824. this._computeHeightQuads();
  39825. }
  39826. var facet = this._getFacetAt(x, z);
  39827. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  39828. // return y in the World system
  39829. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  39830. return tmpVect.y;
  39831. };
  39832. /**
  39833. * Returns a normalized vector (Vector3) orthogonal to the ground
  39834. * at the ground coordinates (x, z) expressed in the World system.
  39835. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  39836. */
  39837. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  39838. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  39839. this.getNormalAtCoordinatesToRef(x, z, normal);
  39840. return normal;
  39841. };
  39842. /**
  39843. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  39844. * at the ground coordinates (x, z) expressed in the World system.
  39845. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  39846. * Returns the GroundMesh.
  39847. */
  39848. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  39849. var world = this.getWorldMatrix();
  39850. var tmpMat = BABYLON.Tmp.Matrix[5];
  39851. world.invertToRef(tmpMat);
  39852. var tmpVect = BABYLON.Tmp.Vector3[8];
  39853. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  39854. x = tmpVect.x;
  39855. z = tmpVect.z;
  39856. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  39857. return this;
  39858. }
  39859. if (!this._heightQuads || this._heightQuads.length == 0) {
  39860. this._initHeightQuads();
  39861. this._computeHeightQuads();
  39862. }
  39863. var facet = this._getFacetAt(x, z);
  39864. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  39865. return this;
  39866. };
  39867. /**
  39868. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  39869. * if the ground has been updated.
  39870. * This can be used in the render loop.
  39871. * Returns the GroundMesh.
  39872. */
  39873. GroundMesh.prototype.updateCoordinateHeights = function () {
  39874. if (!this._heightQuads || this._heightQuads.length == 0) {
  39875. this._initHeightQuads();
  39876. }
  39877. this._computeHeightQuads();
  39878. return this;
  39879. };
  39880. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  39881. GroundMesh.prototype._getFacetAt = function (x, z) {
  39882. // retrieve col and row from x, z coordinates in the ground local system
  39883. var subdivisionsX = this._subdivisionsX;
  39884. var subdivisionsY = this._subdivisionsY;
  39885. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  39886. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  39887. var quad = this._heightQuads[row * this._subdivisionsX + col];
  39888. var facet;
  39889. if (z < quad.slope.x * x + quad.slope.y) {
  39890. facet = quad.facet1;
  39891. }
  39892. else {
  39893. facet = quad.facet2;
  39894. }
  39895. return facet;
  39896. };
  39897. // Creates and populates the heightMap array with "facet" elements :
  39898. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  39899. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  39900. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  39901. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  39902. // Returns the GroundMesh.
  39903. GroundMesh.prototype._initHeightQuads = function () {
  39904. var subdivisionsX = this._subdivisionsX;
  39905. var subdivisionsY = this._subdivisionsY;
  39906. this._heightQuads = new Array();
  39907. for (var row = 0; row < subdivisionsY; row++) {
  39908. for (var col = 0; col < subdivisionsX; col++) {
  39909. 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) };
  39910. this._heightQuads[row * subdivisionsX + col] = quad;
  39911. }
  39912. }
  39913. return this;
  39914. };
  39915. // Compute each quad element values and update the the heightMap array :
  39916. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  39917. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  39918. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  39919. // Returns the GroundMesh.
  39920. GroundMesh.prototype._computeHeightQuads = function () {
  39921. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39922. var v1 = BABYLON.Tmp.Vector3[3];
  39923. var v2 = BABYLON.Tmp.Vector3[2];
  39924. var v3 = BABYLON.Tmp.Vector3[1];
  39925. var v4 = BABYLON.Tmp.Vector3[0];
  39926. var v1v2 = BABYLON.Tmp.Vector3[4];
  39927. var v1v3 = BABYLON.Tmp.Vector3[5];
  39928. var v1v4 = BABYLON.Tmp.Vector3[6];
  39929. var norm1 = BABYLON.Tmp.Vector3[7];
  39930. var norm2 = BABYLON.Tmp.Vector3[8];
  39931. var i = 0;
  39932. var j = 0;
  39933. var k = 0;
  39934. var cd = 0; // 2D slope coefficient : z = cd * x + h
  39935. var h = 0;
  39936. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  39937. var d2 = 0;
  39938. var subdivisionsX = this._subdivisionsX;
  39939. var subdivisionsY = this._subdivisionsY;
  39940. for (var row = 0; row < subdivisionsY; row++) {
  39941. for (var col = 0; col < subdivisionsX; col++) {
  39942. i = col * 3;
  39943. j = row * (subdivisionsX + 1) * 3;
  39944. k = (row + 1) * (subdivisionsX + 1) * 3;
  39945. v1.x = positions[j + i];
  39946. v1.y = positions[j + i + 1];
  39947. v1.z = positions[j + i + 2];
  39948. v2.x = positions[j + i + 3];
  39949. v2.y = positions[j + i + 4];
  39950. v2.z = positions[j + i + 5];
  39951. v3.x = positions[k + i];
  39952. v3.y = positions[k + i + 1];
  39953. v3.z = positions[k + i + 2];
  39954. v4.x = positions[k + i + 3];
  39955. v4.y = positions[k + i + 4];
  39956. v4.z = positions[k + i + 5];
  39957. // 2D slope V1V4
  39958. cd = (v4.z - v1.z) / (v4.x - v1.x);
  39959. h = v1.z - cd * v1.x; // v1 belongs to the slope
  39960. // facet equations :
  39961. // we compute each facet normal vector
  39962. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  39963. // we compute the value d by applying the equation to v1 which belongs to the plane
  39964. // then we store the facet equation in a Vector4
  39965. v2.subtractToRef(v1, v1v2);
  39966. v3.subtractToRef(v1, v1v3);
  39967. v4.subtractToRef(v1, v1v4);
  39968. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  39969. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  39970. norm1.normalize();
  39971. norm2.normalize();
  39972. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  39973. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  39974. var quad = this._heightQuads[row * subdivisionsX + col];
  39975. quad.slope.copyFromFloats(cd, h);
  39976. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  39977. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  39978. }
  39979. }
  39980. return this;
  39981. };
  39982. GroundMesh.prototype.serialize = function (serializationObject) {
  39983. _super.prototype.serialize.call(this, serializationObject);
  39984. serializationObject.subdivisionsX = this._subdivisionsX;
  39985. serializationObject.subdivisionsY = this._subdivisionsY;
  39986. serializationObject.minX = this._minX;
  39987. serializationObject.maxX = this._maxX;
  39988. serializationObject.minZ = this._minZ;
  39989. serializationObject.maxZ = this._maxZ;
  39990. serializationObject.width = this._width;
  39991. serializationObject.height = this._height;
  39992. };
  39993. GroundMesh.Parse = function (parsedMesh, scene) {
  39994. var result = new GroundMesh(parsedMesh.name, scene);
  39995. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  39996. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  39997. result._minX = parsedMesh.minX;
  39998. result._maxX = parsedMesh.maxX;
  39999. result._minZ = parsedMesh.minZ;
  40000. result._maxZ = parsedMesh.maxZ;
  40001. result._width = parsedMesh.width;
  40002. result._height = parsedMesh.height;
  40003. return result;
  40004. };
  40005. return GroundMesh;
  40006. }(BABYLON.Mesh));
  40007. BABYLON.GroundMesh = GroundMesh;
  40008. })(BABYLON || (BABYLON = {}));
  40009. //# sourceMappingURL=babylon.groundMesh.js.map
  40010. var BABYLON;
  40011. (function (BABYLON) {
  40012. /**
  40013. * Creates an instance based on a source mesh.
  40014. */
  40015. var InstancedMesh = (function (_super) {
  40016. __extends(InstancedMesh, _super);
  40017. function InstancedMesh(name, source) {
  40018. var _this = _super.call(this, name, source.getScene()) || this;
  40019. source.instances.push(_this);
  40020. _this._sourceMesh = source;
  40021. _this.position.copyFrom(source.position);
  40022. _this.rotation.copyFrom(source.rotation);
  40023. _this.scaling.copyFrom(source.scaling);
  40024. if (source.rotationQuaternion) {
  40025. _this.rotationQuaternion = source.rotationQuaternion.clone();
  40026. }
  40027. _this.infiniteDistance = source.infiniteDistance;
  40028. _this.setPivotMatrix(source.getPivotMatrix());
  40029. _this.refreshBoundingInfo();
  40030. _this._syncSubMeshes();
  40031. return _this;
  40032. }
  40033. /**
  40034. * Returns the string "InstancedMesh".
  40035. */
  40036. InstancedMesh.prototype.getClassName = function () {
  40037. return "InstancedMesh";
  40038. };
  40039. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  40040. // Methods
  40041. get: function () {
  40042. return this._sourceMesh.receiveShadows;
  40043. },
  40044. enumerable: true,
  40045. configurable: true
  40046. });
  40047. Object.defineProperty(InstancedMesh.prototype, "material", {
  40048. get: function () {
  40049. return this._sourceMesh.material;
  40050. },
  40051. enumerable: true,
  40052. configurable: true
  40053. });
  40054. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  40055. get: function () {
  40056. return this._sourceMesh.visibility;
  40057. },
  40058. enumerable: true,
  40059. configurable: true
  40060. });
  40061. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  40062. get: function () {
  40063. return this._sourceMesh.skeleton;
  40064. },
  40065. enumerable: true,
  40066. configurable: true
  40067. });
  40068. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  40069. get: function () {
  40070. return this._sourceMesh.renderingGroupId;
  40071. },
  40072. enumerable: true,
  40073. configurable: true
  40074. });
  40075. /**
  40076. * Returns the total number of vertices (integer).
  40077. */
  40078. InstancedMesh.prototype.getTotalVertices = function () {
  40079. return this._sourceMesh.getTotalVertices();
  40080. };
  40081. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  40082. get: function () {
  40083. return this._sourceMesh;
  40084. },
  40085. enumerable: true,
  40086. configurable: true
  40087. });
  40088. /**
  40089. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  40090. */
  40091. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  40092. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  40093. };
  40094. /**
  40095. * Sets the vertex data of the mesh geometry for the requested `kind`.
  40096. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  40097. * The `data` are either a numeric array either a Float32Array.
  40098. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  40099. * 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).
  40100. * Note that a new underlying VertexBuffer object is created each call.
  40101. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  40102. *
  40103. * Possible `kind` values :
  40104. * - BABYLON.VertexBuffer.PositionKind
  40105. * - BABYLON.VertexBuffer.UVKind
  40106. * - BABYLON.VertexBuffer.UV2Kind
  40107. * - BABYLON.VertexBuffer.UV3Kind
  40108. * - BABYLON.VertexBuffer.UV4Kind
  40109. * - BABYLON.VertexBuffer.UV5Kind
  40110. * - BABYLON.VertexBuffer.UV6Kind
  40111. * - BABYLON.VertexBuffer.ColorKind
  40112. * - BABYLON.VertexBuffer.MatricesIndicesKind
  40113. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  40114. * - BABYLON.VertexBuffer.MatricesWeightsKind
  40115. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  40116. *
  40117. * Returns the Mesh.
  40118. */
  40119. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  40120. if (this.sourceMesh) {
  40121. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  40122. }
  40123. return this.sourceMesh;
  40124. };
  40125. /**
  40126. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  40127. * If the mesh has no geometry, it is simply returned as it is.
  40128. * The `data` are either a numeric array either a Float32Array.
  40129. * No new underlying VertexBuffer object is created.
  40130. * 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.
  40131. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  40132. *
  40133. * Possible `kind` values :
  40134. * - BABYLON.VertexBuffer.PositionKind
  40135. * - BABYLON.VertexBuffer.UVKind
  40136. * - BABYLON.VertexBuffer.UV2Kind
  40137. * - BABYLON.VertexBuffer.UV3Kind
  40138. * - BABYLON.VertexBuffer.UV4Kind
  40139. * - BABYLON.VertexBuffer.UV5Kind
  40140. * - BABYLON.VertexBuffer.UV6Kind
  40141. * - BABYLON.VertexBuffer.ColorKind
  40142. * - BABYLON.VertexBuffer.MatricesIndicesKind
  40143. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  40144. * - BABYLON.VertexBuffer.MatricesWeightsKind
  40145. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  40146. *
  40147. * Returns the Mesh.
  40148. */
  40149. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  40150. if (this.sourceMesh) {
  40151. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  40152. }
  40153. return this.sourceMesh;
  40154. };
  40155. /**
  40156. * Sets the mesh indices.
  40157. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  40158. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  40159. * This method creates a new index buffer each call.
  40160. * Returns the Mesh.
  40161. */
  40162. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  40163. if (this.sourceMesh) {
  40164. this.sourceMesh.setIndices(indices, totalVertices);
  40165. }
  40166. return this.sourceMesh;
  40167. };
  40168. /**
  40169. * Boolean : True if the mesh owns the requested kind of data.
  40170. */
  40171. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  40172. return this._sourceMesh.isVerticesDataPresent(kind);
  40173. };
  40174. /**
  40175. * Returns an array of indices (IndicesArray).
  40176. */
  40177. InstancedMesh.prototype.getIndices = function () {
  40178. return this._sourceMesh.getIndices();
  40179. };
  40180. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  40181. get: function () {
  40182. return this._sourceMesh._positions;
  40183. },
  40184. enumerable: true,
  40185. configurable: true
  40186. });
  40187. /**
  40188. * Sets a new updated BoundingInfo to the mesh.
  40189. * Returns the mesh.
  40190. */
  40191. InstancedMesh.prototype.refreshBoundingInfo = function () {
  40192. var meshBB = this._sourceMesh.getBoundingInfo();
  40193. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  40194. this._updateBoundingInfo();
  40195. return this;
  40196. };
  40197. InstancedMesh.prototype._preActivate = function () {
  40198. if (this._currentLOD) {
  40199. this._currentLOD._preActivate();
  40200. }
  40201. return this;
  40202. };
  40203. InstancedMesh.prototype._activate = function (renderId) {
  40204. if (this._currentLOD) {
  40205. this._currentLOD._registerInstanceForRenderId(this, renderId);
  40206. }
  40207. return this;
  40208. };
  40209. /**
  40210. * Returns the current associated LOD AbstractMesh.
  40211. */
  40212. InstancedMesh.prototype.getLOD = function (camera) {
  40213. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  40214. if (this._currentLOD === this.sourceMesh) {
  40215. return this;
  40216. }
  40217. return this._currentLOD;
  40218. };
  40219. InstancedMesh.prototype._syncSubMeshes = function () {
  40220. this.releaseSubMeshes();
  40221. if (this._sourceMesh.subMeshes) {
  40222. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  40223. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  40224. }
  40225. }
  40226. return this;
  40227. };
  40228. InstancedMesh.prototype._generatePointsArray = function () {
  40229. return this._sourceMesh._generatePointsArray();
  40230. };
  40231. /**
  40232. * Creates a new InstancedMesh from the current mesh.
  40233. * - name (string) : the cloned mesh name
  40234. * - newParent (optional Node) : the optional Node to parent the clone to.
  40235. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  40236. *
  40237. * Returns the clone.
  40238. */
  40239. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  40240. var result = this._sourceMesh.createInstance(name);
  40241. // Deep copy
  40242. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  40243. // Bounding info
  40244. this.refreshBoundingInfo();
  40245. // Parent
  40246. if (newParent) {
  40247. result.parent = newParent;
  40248. }
  40249. if (!doNotCloneChildren) {
  40250. // Children
  40251. for (var index = 0; index < this.getScene().meshes.length; index++) {
  40252. var mesh = this.getScene().meshes[index];
  40253. if (mesh.parent === this) {
  40254. mesh.clone(mesh.name, result);
  40255. }
  40256. }
  40257. }
  40258. result.computeWorldMatrix(true);
  40259. return result;
  40260. };
  40261. /**
  40262. * Disposes the InstancedMesh.
  40263. * Returns nothing.
  40264. */
  40265. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  40266. // Remove from mesh
  40267. var index = this._sourceMesh.instances.indexOf(this);
  40268. this._sourceMesh.instances.splice(index, 1);
  40269. _super.prototype.dispose.call(this, doNotRecurse);
  40270. };
  40271. return InstancedMesh;
  40272. }(BABYLON.AbstractMesh));
  40273. BABYLON.InstancedMesh = InstancedMesh;
  40274. })(BABYLON || (BABYLON = {}));
  40275. //# sourceMappingURL=babylon.instancedMesh.js.map
  40276. /// <reference path="babylon.mesh.ts" />
  40277. var BABYLON;
  40278. (function (BABYLON) {
  40279. var LinesMesh = (function (_super) {
  40280. __extends(LinesMesh, _super);
  40281. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  40282. if (parent === void 0) { parent = null; }
  40283. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  40284. _this.useVertexColor = useVertexColor;
  40285. _this.color = new BABYLON.Color3(1, 1, 1);
  40286. _this.alpha = 1;
  40287. if (source) {
  40288. _this.color = source.color.clone();
  40289. _this.alpha = source.alpha;
  40290. _this.useVertexColor = source.useVertexColor;
  40291. }
  40292. _this._intersectionThreshold = 0.1;
  40293. var options = {
  40294. attributes: [BABYLON.VertexBuffer.PositionKind],
  40295. uniforms: ["world", "viewProjection"],
  40296. needAlphaBlending: false,
  40297. };
  40298. if (!useVertexColor) {
  40299. options.uniforms.push("color");
  40300. options.needAlphaBlending = true;
  40301. }
  40302. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  40303. return _this;
  40304. }
  40305. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  40306. /**
  40307. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  40308. * This margin is expressed in world space coordinates, so its value may vary.
  40309. * Default value is 0.1
  40310. * @returns the intersection Threshold value.
  40311. */
  40312. get: function () {
  40313. return this._intersectionThreshold;
  40314. },
  40315. /**
  40316. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  40317. * This margin is expressed in world space coordinates, so its value may vary.
  40318. * @param value the new threshold to apply
  40319. */
  40320. set: function (value) {
  40321. if (this._intersectionThreshold === value) {
  40322. return;
  40323. }
  40324. this._intersectionThreshold = value;
  40325. if (this.geometry) {
  40326. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  40327. }
  40328. },
  40329. enumerable: true,
  40330. configurable: true
  40331. });
  40332. /**
  40333. * Returns the string "LineMesh"
  40334. */
  40335. LinesMesh.prototype.getClassName = function () {
  40336. return "LinesMesh";
  40337. };
  40338. Object.defineProperty(LinesMesh.prototype, "material", {
  40339. get: function () {
  40340. return this._colorShader;
  40341. },
  40342. enumerable: true,
  40343. configurable: true
  40344. });
  40345. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  40346. get: function () {
  40347. return false;
  40348. },
  40349. enumerable: true,
  40350. configurable: true
  40351. });
  40352. LinesMesh.prototype.createInstance = function (name) {
  40353. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  40354. return null;
  40355. };
  40356. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  40357. // VBOs
  40358. this._geometry._bind(this._colorShader.getEffect());
  40359. // Color
  40360. if (!this.useVertexColor) {
  40361. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  40362. }
  40363. return this;
  40364. };
  40365. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  40366. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  40367. return this;
  40368. }
  40369. var engine = this.getScene().getEngine();
  40370. // Draw order
  40371. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  40372. return this;
  40373. };
  40374. LinesMesh.prototype.dispose = function (doNotRecurse) {
  40375. this._colorShader.dispose();
  40376. _super.prototype.dispose.call(this, doNotRecurse);
  40377. };
  40378. /**
  40379. * Returns a new LineMesh object cloned from the current one.
  40380. */
  40381. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  40382. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  40383. };
  40384. return LinesMesh;
  40385. }(BABYLON.Mesh));
  40386. BABYLON.LinesMesh = LinesMesh;
  40387. })(BABYLON || (BABYLON = {}));
  40388. //# sourceMappingURL=babylon.linesMesh.js.map
  40389. var BABYLON;
  40390. (function (BABYLON) {
  40391. var StandardMaterialDefines = (function (_super) {
  40392. __extends(StandardMaterialDefines, _super);
  40393. function StandardMaterialDefines() {
  40394. var _this = _super.call(this) || this;
  40395. _this.DIFFUSE = false;
  40396. _this.AMBIENT = false;
  40397. _this.OPACITY = false;
  40398. _this.OPACITYRGB = false;
  40399. _this.REFLECTION = false;
  40400. _this.EMISSIVE = false;
  40401. _this.SPECULAR = false;
  40402. _this.BUMP = false;
  40403. _this.PARALLAX = false;
  40404. _this.PARALLAXOCCLUSION = false;
  40405. _this.SPECULAROVERALPHA = false;
  40406. _this.CLIPPLANE = false;
  40407. _this.ALPHATEST = false;
  40408. _this.ALPHAFROMDIFFUSE = false;
  40409. _this.POINTSIZE = false;
  40410. _this.FOG = false;
  40411. _this.SPECULARTERM = false;
  40412. _this.DIFFUSEFRESNEL = false;
  40413. _this.OPACITYFRESNEL = false;
  40414. _this.REFLECTIONFRESNEL = false;
  40415. _this.REFRACTIONFRESNEL = false;
  40416. _this.EMISSIVEFRESNEL = false;
  40417. _this.FRESNEL = false;
  40418. _this.NORMAL = false;
  40419. _this.UV1 = false;
  40420. _this.UV2 = false;
  40421. _this.VERTEXCOLOR = false;
  40422. _this.VERTEXALPHA = false;
  40423. _this.NUM_BONE_INFLUENCERS = 0;
  40424. _this.BonesPerMesh = 0;
  40425. _this.INSTANCES = false;
  40426. _this.GLOSSINESS = false;
  40427. _this.ROUGHNESS = false;
  40428. _this.EMISSIVEASILLUMINATION = false;
  40429. _this.LINKEMISSIVEWITHDIFFUSE = false;
  40430. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  40431. _this.LIGHTMAP = false;
  40432. _this.USELIGHTMAPASSHADOWMAP = false;
  40433. _this.REFLECTIONMAP_3D = false;
  40434. _this.REFLECTIONMAP_SPHERICAL = false;
  40435. _this.REFLECTIONMAP_PLANAR = false;
  40436. _this.REFLECTIONMAP_CUBIC = false;
  40437. _this.REFLECTIONMAP_PROJECTION = false;
  40438. _this.REFLECTIONMAP_SKYBOX = false;
  40439. _this.REFLECTIONMAP_EXPLICIT = false;
  40440. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40441. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40442. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40443. _this.INVERTCUBICMAP = false;
  40444. _this.LOGARITHMICDEPTH = false;
  40445. _this.REFRACTION = false;
  40446. _this.REFRACTIONMAP_3D = false;
  40447. _this.REFLECTIONOVERALPHA = false;
  40448. _this.INVERTNORMALMAPX = false;
  40449. _this.INVERTNORMALMAPY = false;
  40450. _this.TWOSIDEDLIGHTING = false;
  40451. _this.SHADOWFLOAT = false;
  40452. _this.CAMERACOLORGRADING = false;
  40453. _this.CAMERACOLORCURVES = false;
  40454. _this.MORPHTARGETS = false;
  40455. _this.MORPHTARGETS_NORMAL = false;
  40456. _this.MORPHTARGETS_TANGENT = false;
  40457. _this.NUM_MORPH_INFLUENCERS = 0;
  40458. _this.USERIGHTHANDEDSYSTEM = false;
  40459. _this.rebuild();
  40460. return _this;
  40461. }
  40462. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  40463. var modes = [
  40464. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  40465. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  40466. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  40467. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  40468. ];
  40469. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  40470. var mode = modes_1[_i];
  40471. this[mode] = (mode === modeToEnable);
  40472. }
  40473. };
  40474. return StandardMaterialDefines;
  40475. }(BABYLON.MaterialDefines));
  40476. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  40477. var StandardMaterial = (function (_super) {
  40478. __extends(StandardMaterial, _super);
  40479. function StandardMaterial(name, scene) {
  40480. var _this = _super.call(this, name, scene) || this;
  40481. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  40482. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  40483. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  40484. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  40485. _this.specularPower = 64;
  40486. _this._useAlphaFromDiffuseTexture = false;
  40487. _this._useEmissiveAsIllumination = false;
  40488. _this._linkEmissiveWithDiffuse = false;
  40489. _this._useSpecularOverAlpha = false;
  40490. _this._useReflectionOverAlpha = false;
  40491. _this._disableLighting = false;
  40492. _this._useParallax = false;
  40493. _this._useParallaxOcclusion = false;
  40494. _this.parallaxScaleBias = 0.05;
  40495. _this._roughness = 0;
  40496. _this.indexOfRefraction = 0.98;
  40497. _this.invertRefractionY = true;
  40498. _this._useLightmapAsShadowmap = false;
  40499. _this._useReflectionFresnelFromSpecular = false;
  40500. _this._useGlossinessFromSpecularMapAlpha = false;
  40501. _this._maxSimultaneousLights = 4;
  40502. /**
  40503. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  40504. */
  40505. _this._invertNormalMapX = false;
  40506. /**
  40507. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  40508. */
  40509. _this._invertNormalMapY = false;
  40510. /**
  40511. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40512. */
  40513. _this._twoSidedLighting = false;
  40514. /**
  40515. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  40516. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  40517. * 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;
  40518. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  40519. */
  40520. _this._cameraColorCurves = null;
  40521. _this._renderTargets = new BABYLON.SmartArray(16);
  40522. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  40523. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  40524. _this.getRenderTargetTextures = function () {
  40525. _this._renderTargets.reset();
  40526. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  40527. _this._renderTargets.push(_this._reflectionTexture);
  40528. }
  40529. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  40530. _this._renderTargets.push(_this._refractionTexture);
  40531. }
  40532. return _this._renderTargets;
  40533. };
  40534. return _this;
  40535. }
  40536. StandardMaterial.prototype.getClassName = function () {
  40537. return "StandardMaterial";
  40538. };
  40539. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  40540. get: function () {
  40541. return this._useLogarithmicDepth;
  40542. },
  40543. set: function (value) {
  40544. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  40545. this._markAllSubMeshesAsMiscDirty();
  40546. },
  40547. enumerable: true,
  40548. configurable: true
  40549. });
  40550. StandardMaterial.prototype.needAlphaBlending = function () {
  40551. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  40552. };
  40553. StandardMaterial.prototype.needAlphaTesting = function () {
  40554. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  40555. };
  40556. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  40557. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  40558. };
  40559. StandardMaterial.prototype.getAlphaTestTexture = function () {
  40560. return this._diffuseTexture;
  40561. };
  40562. /**
  40563. * Child classes can use it to update shaders
  40564. */
  40565. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  40566. if (this.isFrozen) {
  40567. if (this._wasPreviouslyReady && subMesh.effect) {
  40568. return true;
  40569. }
  40570. }
  40571. if (!subMesh._materialDefines) {
  40572. subMesh._materialDefines = new StandardMaterialDefines();
  40573. }
  40574. var scene = this.getScene();
  40575. var defines = subMesh._materialDefines;
  40576. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  40577. if (defines._renderId === scene.getRenderId()) {
  40578. return true;
  40579. }
  40580. }
  40581. var engine = scene.getEngine();
  40582. // Lights
  40583. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  40584. // Textures
  40585. if (defines._areTexturesDirty) {
  40586. defines._needUVs = false;
  40587. if (scene.texturesEnabled) {
  40588. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40589. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  40590. return false;
  40591. }
  40592. else {
  40593. defines._needUVs = true;
  40594. defines.DIFFUSE = true;
  40595. }
  40596. }
  40597. else {
  40598. defines.DIFFUSE = false;
  40599. }
  40600. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40601. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  40602. return false;
  40603. }
  40604. else {
  40605. defines._needUVs = true;
  40606. defines.AMBIENT = true;
  40607. }
  40608. }
  40609. else {
  40610. defines.AMBIENT = false;
  40611. }
  40612. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40613. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  40614. return false;
  40615. }
  40616. else {
  40617. defines._needUVs = true;
  40618. defines.OPACITY = true;
  40619. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  40620. }
  40621. }
  40622. else {
  40623. defines.OPACITY = false;
  40624. }
  40625. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40626. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  40627. return false;
  40628. }
  40629. else {
  40630. defines._needNormals = true;
  40631. defines.REFLECTION = true;
  40632. defines.ROUGHNESS = (this._roughness > 0);
  40633. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  40634. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  40635. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  40636. switch (this._reflectionTexture.coordinatesMode) {
  40637. case BABYLON.Texture.CUBIC_MODE:
  40638. case BABYLON.Texture.INVCUBIC_MODE:
  40639. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  40640. break;
  40641. case BABYLON.Texture.EXPLICIT_MODE:
  40642. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  40643. break;
  40644. case BABYLON.Texture.PLANAR_MODE:
  40645. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  40646. break;
  40647. case BABYLON.Texture.PROJECTION_MODE:
  40648. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  40649. break;
  40650. case BABYLON.Texture.SKYBOX_MODE:
  40651. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  40652. break;
  40653. case BABYLON.Texture.SPHERICAL_MODE:
  40654. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  40655. break;
  40656. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  40657. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  40658. break;
  40659. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  40660. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  40661. break;
  40662. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  40663. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  40664. break;
  40665. }
  40666. }
  40667. }
  40668. else {
  40669. defines.REFLECTION = false;
  40670. }
  40671. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40672. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  40673. return false;
  40674. }
  40675. else {
  40676. defines._needUVs = true;
  40677. defines.EMISSIVE = true;
  40678. }
  40679. }
  40680. else {
  40681. defines.EMISSIVE = false;
  40682. }
  40683. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40684. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  40685. return false;
  40686. }
  40687. else {
  40688. defines._needUVs = true;
  40689. defines.LIGHTMAP = true;
  40690. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  40691. }
  40692. }
  40693. else {
  40694. defines.LIGHTMAP = false;
  40695. }
  40696. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40697. if (!this._specularTexture.isReadyOrNotBlocking()) {
  40698. return false;
  40699. }
  40700. else {
  40701. defines._needUVs = true;
  40702. defines.SPECULAR = true;
  40703. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  40704. }
  40705. }
  40706. else {
  40707. defines.SPECULAR = false;
  40708. }
  40709. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  40710. // Bump texure can not be not blocking.
  40711. if (!this._bumpTexture.isReady()) {
  40712. return false;
  40713. }
  40714. else {
  40715. defines._needUVs = true;
  40716. defines.BUMP = true;
  40717. defines.INVERTNORMALMAPX = this.invertNormalMapX;
  40718. defines.INVERTNORMALMAPY = this.invertNormalMapY;
  40719. defines.PARALLAX = this._useParallax;
  40720. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  40721. }
  40722. }
  40723. else {
  40724. defines.BUMP = false;
  40725. }
  40726. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40727. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  40728. return false;
  40729. }
  40730. else {
  40731. defines._needUVs = true;
  40732. defines.REFRACTION = true;
  40733. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  40734. }
  40735. }
  40736. else {
  40737. defines.REFRACTION = false;
  40738. }
  40739. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  40740. // Camera Color Grading can not be none blocking.
  40741. if (!this._cameraColorGradingTexture.isReady()) {
  40742. return false;
  40743. }
  40744. else {
  40745. defines.CAMERACOLORGRADING = true;
  40746. }
  40747. }
  40748. else {
  40749. defines.CAMERACOLORGRADING = false;
  40750. }
  40751. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  40752. }
  40753. else {
  40754. defines.DIFFUSE = false;
  40755. defines.AMBIENT = false;
  40756. defines.OPACITY = false;
  40757. defines.REFLECTION = false;
  40758. defines.EMISSIVE = false;
  40759. defines.LIGHTMAP = false;
  40760. defines.BUMP = false;
  40761. defines.REFRACTION = false;
  40762. defines.CAMERACOLORGRADING = false;
  40763. }
  40764. defines.CAMERACOLORCURVES = (this._cameraColorCurves !== undefined && this._cameraColorCurves !== null);
  40765. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  40766. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  40767. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  40768. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  40769. }
  40770. if (defines._areFresnelDirty) {
  40771. if (StandardMaterial.FresnelEnabled) {
  40772. // Fresnel
  40773. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  40774. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  40775. this._reflectionFresnelParameters) {
  40776. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  40777. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  40778. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  40779. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  40780. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  40781. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  40782. defines._needNormals = true;
  40783. defines.FRESNEL = true;
  40784. }
  40785. }
  40786. else {
  40787. defines.FRESNEL = false;
  40788. }
  40789. }
  40790. // Misc.
  40791. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  40792. // Attribs
  40793. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  40794. // Values that need to be evaluated on every frame
  40795. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  40796. if (scene._mirroredCameraPosition && defines.BUMP) {
  40797. defines.INVERTNORMALMAPX = !this.invertNormalMapX;
  40798. defines.INVERTNORMALMAPY = !this.invertNormalMapY;
  40799. defines.markAsUnprocessed();
  40800. }
  40801. // Get correct effect
  40802. if (defines.isDirty) {
  40803. defines.markAsProcessed();
  40804. scene.resetCachedMaterial();
  40805. // Fallbacks
  40806. var fallbacks = new BABYLON.EffectFallbacks();
  40807. if (defines.REFLECTION) {
  40808. fallbacks.addFallback(0, "REFLECTION");
  40809. }
  40810. if (defines.SPECULAR) {
  40811. fallbacks.addFallback(0, "SPECULAR");
  40812. }
  40813. if (defines.BUMP) {
  40814. fallbacks.addFallback(0, "BUMP");
  40815. }
  40816. if (defines.PARALLAX) {
  40817. fallbacks.addFallback(1, "PARALLAX");
  40818. }
  40819. if (defines.PARALLAXOCCLUSION) {
  40820. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  40821. }
  40822. if (defines.SPECULAROVERALPHA) {
  40823. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  40824. }
  40825. if (defines.FOG) {
  40826. fallbacks.addFallback(1, "FOG");
  40827. }
  40828. if (defines.POINTSIZE) {
  40829. fallbacks.addFallback(0, "POINTSIZE");
  40830. }
  40831. if (defines.LOGARITHMICDEPTH) {
  40832. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  40833. }
  40834. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  40835. if (defines.SPECULARTERM) {
  40836. fallbacks.addFallback(0, "SPECULARTERM");
  40837. }
  40838. if (defines.DIFFUSEFRESNEL) {
  40839. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  40840. }
  40841. if (defines.OPACITYFRESNEL) {
  40842. fallbacks.addFallback(2, "OPACITYFRESNEL");
  40843. }
  40844. if (defines.REFLECTIONFRESNEL) {
  40845. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  40846. }
  40847. if (defines.EMISSIVEFRESNEL) {
  40848. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  40849. }
  40850. if (defines.FRESNEL) {
  40851. fallbacks.addFallback(4, "FRESNEL");
  40852. }
  40853. //Attributes
  40854. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40855. if (defines.NORMAL) {
  40856. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40857. }
  40858. if (defines.UV1) {
  40859. attribs.push(BABYLON.VertexBuffer.UVKind);
  40860. }
  40861. if (defines.UV2) {
  40862. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40863. }
  40864. if (defines.VERTEXCOLOR) {
  40865. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40866. }
  40867. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40868. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40869. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40870. var shaderName = "default";
  40871. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  40872. "vFogInfos", "vFogColor", "pointSize",
  40873. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40874. "mBones",
  40875. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  40876. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  40877. "logarithmicDepthConstant"
  40878. ];
  40879. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  40880. var uniformBuffers = ["Material", "Scene"];
  40881. if (defines.CAMERACOLORCURVES) {
  40882. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  40883. }
  40884. if (defines.CAMERACOLORGRADING) {
  40885. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  40886. }
  40887. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40888. uniformsNames: uniforms,
  40889. uniformBuffersNames: uniformBuffers,
  40890. samplers: samplers,
  40891. defines: defines,
  40892. maxSimultaneousLights: this._maxSimultaneousLights
  40893. });
  40894. if (this.customShaderNameResolve) {
  40895. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  40896. }
  40897. var join = defines.toString();
  40898. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  40899. attributes: attribs,
  40900. uniformsNames: uniforms,
  40901. uniformBuffersNames: uniformBuffers,
  40902. samplers: samplers,
  40903. defines: join,
  40904. fallbacks: fallbacks,
  40905. onCompiled: this.onCompiled,
  40906. onError: this.onError,
  40907. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40908. }, engine), defines);
  40909. this.buildUniformLayout();
  40910. }
  40911. if (!subMesh.effect.isReady()) {
  40912. return false;
  40913. }
  40914. defines._renderId = scene.getRenderId();
  40915. this._wasPreviouslyReady = true;
  40916. return true;
  40917. };
  40918. StandardMaterial.prototype.buildUniformLayout = function () {
  40919. // Order is important !
  40920. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  40921. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  40922. this._uniformBuffer.addUniform("opacityParts", 4);
  40923. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  40924. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  40925. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  40926. this._uniformBuffer.addUniform("refractionRightColor", 4);
  40927. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  40928. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  40929. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  40930. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  40931. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  40932. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  40933. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  40934. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  40935. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  40936. this._uniformBuffer.addUniform("vBumpInfos", 3);
  40937. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  40938. this._uniformBuffer.addUniform("ambientMatrix", 16);
  40939. this._uniformBuffer.addUniform("opacityMatrix", 16);
  40940. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  40941. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  40942. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  40943. this._uniformBuffer.addUniform("specularMatrix", 16);
  40944. this._uniformBuffer.addUniform("bumpMatrix", 16);
  40945. this._uniformBuffer.addUniform("refractionMatrix", 16);
  40946. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  40947. this._uniformBuffer.addUniform("vSpecularColor", 4);
  40948. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  40949. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  40950. this._uniformBuffer.addUniform("pointSize", 1);
  40951. this._uniformBuffer.create();
  40952. };
  40953. StandardMaterial.prototype.unbind = function () {
  40954. if (this._activeEffect) {
  40955. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  40956. this._activeEffect.setTexture("reflection2DSampler", null);
  40957. }
  40958. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  40959. this._activeEffect.setTexture("refraction2DSampler", null);
  40960. }
  40961. }
  40962. _super.prototype.unbind.call(this);
  40963. };
  40964. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  40965. var scene = this.getScene();
  40966. var defines = subMesh._materialDefines;
  40967. if (!defines) {
  40968. return;
  40969. }
  40970. var effect = subMesh.effect;
  40971. this._activeEffect = effect;
  40972. // Matrices
  40973. this.bindOnlyWorldMatrix(world);
  40974. // Bones
  40975. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  40976. if (this._mustRebind(scene, effect, mesh.visibility)) {
  40977. this._uniformBuffer.bindToEffect(effect, "Material");
  40978. this.bindViewProjection(effect);
  40979. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  40980. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  40981. // Fresnel
  40982. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  40983. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  40984. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  40985. }
  40986. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  40987. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  40988. }
  40989. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  40990. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  40991. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  40992. }
  40993. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  40994. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  40995. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  40996. }
  40997. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  40998. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  40999. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  41000. }
  41001. }
  41002. // Textures
  41003. if (scene.texturesEnabled) {
  41004. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41005. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  41006. this._uniformBuffer.updateMatrix("diffuseMatrix", this._diffuseTexture.getTextureMatrix());
  41007. }
  41008. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41009. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  41010. this._uniformBuffer.updateMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  41011. }
  41012. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41013. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41014. this._uniformBuffer.updateMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  41015. }
  41016. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41017. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  41018. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  41019. }
  41020. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41021. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41022. this._uniformBuffer.updateMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  41023. }
  41024. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41025. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41026. this._uniformBuffer.updateMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  41027. }
  41028. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41029. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  41030. this._uniformBuffer.updateMatrix("specularMatrix", this._specularTexture.getTextureMatrix());
  41031. }
  41032. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  41033. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  41034. this._uniformBuffer.updateMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  41035. }
  41036. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  41037. var depth = 1.0;
  41038. if (!this._refractionTexture.isCube) {
  41039. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  41040. if (this._refractionTexture.depth) {
  41041. depth = this._refractionTexture.depth;
  41042. }
  41043. }
  41044. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  41045. }
  41046. }
  41047. // Point size
  41048. if (this.pointsCloud) {
  41049. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  41050. }
  41051. if (defines.SPECULARTERM) {
  41052. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  41053. }
  41054. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  41055. // Diffuse
  41056. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  41057. }
  41058. // Textures
  41059. if (scene.texturesEnabled) {
  41060. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  41061. effect.setTexture("diffuseSampler", this._diffuseTexture);
  41062. }
  41063. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  41064. effect.setTexture("ambientSampler", this._ambientTexture);
  41065. }
  41066. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  41067. effect.setTexture("opacitySampler", this._opacityTexture);
  41068. }
  41069. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  41070. if (this._reflectionTexture.isCube) {
  41071. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  41072. }
  41073. else {
  41074. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  41075. }
  41076. }
  41077. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  41078. effect.setTexture("emissiveSampler", this._emissiveTexture);
  41079. }
  41080. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  41081. effect.setTexture("lightmapSampler", this._lightmapTexture);
  41082. }
  41083. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  41084. effect.setTexture("specularSampler", this._specularTexture);
  41085. }
  41086. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  41087. effect.setTexture("bumpSampler", this._bumpTexture);
  41088. }
  41089. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  41090. var depth = 1.0;
  41091. if (this._refractionTexture.isCube) {
  41092. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  41093. }
  41094. else {
  41095. effect.setTexture("refraction2DSampler", this._refractionTexture);
  41096. }
  41097. }
  41098. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  41099. BABYLON.ColorGradingTexture.Bind(this._cameraColorGradingTexture, effect);
  41100. }
  41101. }
  41102. // Clip plane
  41103. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  41104. // Colors
  41105. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  41106. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  41107. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  41108. }
  41109. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  41110. // Lights
  41111. if (scene.lightsEnabled && !this._disableLighting) {
  41112. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  41113. }
  41114. // View
  41115. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  41116. this.bindView(effect);
  41117. }
  41118. // Fog
  41119. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  41120. // Morph targets
  41121. if (defines.NUM_MORPH_INFLUENCERS) {
  41122. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  41123. }
  41124. // Log. depth
  41125. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  41126. // Color Curves
  41127. if (this._cameraColorCurves) {
  41128. BABYLON.ColorCurves.Bind(this._cameraColorCurves, effect);
  41129. }
  41130. }
  41131. this._uniformBuffer.update();
  41132. this._afterBind(mesh, this._activeEffect);
  41133. };
  41134. StandardMaterial.prototype.getAnimatables = function () {
  41135. var results = [];
  41136. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  41137. results.push(this._diffuseTexture);
  41138. }
  41139. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  41140. results.push(this._ambientTexture);
  41141. }
  41142. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  41143. results.push(this._opacityTexture);
  41144. }
  41145. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  41146. results.push(this._reflectionTexture);
  41147. }
  41148. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  41149. results.push(this._emissiveTexture);
  41150. }
  41151. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  41152. results.push(this._specularTexture);
  41153. }
  41154. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  41155. results.push(this._bumpTexture);
  41156. }
  41157. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  41158. results.push(this._lightmapTexture);
  41159. }
  41160. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  41161. results.push(this._refractionTexture);
  41162. }
  41163. if (this._cameraColorGradingTexture && this._cameraColorGradingTexture.animations && this._cameraColorGradingTexture.animations.length > 0) {
  41164. results.push(this._cameraColorGradingTexture);
  41165. }
  41166. return results;
  41167. };
  41168. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41169. if (forceDisposeTextures) {
  41170. if (this._diffuseTexture) {
  41171. this._diffuseTexture.dispose();
  41172. }
  41173. if (this._ambientTexture) {
  41174. this._ambientTexture.dispose();
  41175. }
  41176. if (this._opacityTexture) {
  41177. this._opacityTexture.dispose();
  41178. }
  41179. if (this._reflectionTexture) {
  41180. this._reflectionTexture.dispose();
  41181. }
  41182. if (this._emissiveTexture) {
  41183. this._emissiveTexture.dispose();
  41184. }
  41185. if (this._specularTexture) {
  41186. this._specularTexture.dispose();
  41187. }
  41188. if (this._bumpTexture) {
  41189. this._bumpTexture.dispose();
  41190. }
  41191. if (this._lightmapTexture) {
  41192. this._lightmapTexture.dispose();
  41193. }
  41194. if (this._refractionTexture) {
  41195. this._refractionTexture.dispose();
  41196. }
  41197. if (this._cameraColorGradingTexture) {
  41198. this._cameraColorGradingTexture.dispose();
  41199. }
  41200. }
  41201. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41202. };
  41203. StandardMaterial.prototype.clone = function (name) {
  41204. var _this = this;
  41205. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  41206. result.name = name;
  41207. result.id = name;
  41208. return result;
  41209. };
  41210. StandardMaterial.prototype.serialize = function () {
  41211. return BABYLON.SerializationHelper.Serialize(this);
  41212. };
  41213. // Statics
  41214. StandardMaterial.Parse = function (source, scene, rootUrl) {
  41215. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  41216. };
  41217. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  41218. get: function () {
  41219. return StandardMaterial._DiffuseTextureEnabled;
  41220. },
  41221. set: function (value) {
  41222. if (StandardMaterial._DiffuseTextureEnabled === value) {
  41223. return;
  41224. }
  41225. StandardMaterial._DiffuseTextureEnabled = value;
  41226. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41227. },
  41228. enumerable: true,
  41229. configurable: true
  41230. });
  41231. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  41232. get: function () {
  41233. return StandardMaterial._AmbientTextureEnabled;
  41234. },
  41235. set: function (value) {
  41236. if (StandardMaterial._AmbientTextureEnabled === value) {
  41237. return;
  41238. }
  41239. StandardMaterial._AmbientTextureEnabled = value;
  41240. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41241. },
  41242. enumerable: true,
  41243. configurable: true
  41244. });
  41245. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  41246. get: function () {
  41247. return StandardMaterial._OpacityTextureEnabled;
  41248. },
  41249. set: function (value) {
  41250. if (StandardMaterial._OpacityTextureEnabled === value) {
  41251. return;
  41252. }
  41253. StandardMaterial._OpacityTextureEnabled = value;
  41254. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41255. },
  41256. enumerable: true,
  41257. configurable: true
  41258. });
  41259. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  41260. get: function () {
  41261. return StandardMaterial._ReflectionTextureEnabled;
  41262. },
  41263. set: function (value) {
  41264. if (StandardMaterial._ReflectionTextureEnabled === value) {
  41265. return;
  41266. }
  41267. StandardMaterial._ReflectionTextureEnabled = value;
  41268. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41269. },
  41270. enumerable: true,
  41271. configurable: true
  41272. });
  41273. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  41274. get: function () {
  41275. return StandardMaterial._EmissiveTextureEnabled;
  41276. },
  41277. set: function (value) {
  41278. if (StandardMaterial._EmissiveTextureEnabled === value) {
  41279. return;
  41280. }
  41281. StandardMaterial._EmissiveTextureEnabled = value;
  41282. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41283. },
  41284. enumerable: true,
  41285. configurable: true
  41286. });
  41287. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  41288. get: function () {
  41289. return StandardMaterial._SpecularTextureEnabled;
  41290. },
  41291. set: function (value) {
  41292. if (StandardMaterial._SpecularTextureEnabled === value) {
  41293. return;
  41294. }
  41295. StandardMaterial._SpecularTextureEnabled = value;
  41296. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41297. },
  41298. enumerable: true,
  41299. configurable: true
  41300. });
  41301. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  41302. get: function () {
  41303. return StandardMaterial._BumpTextureEnabled;
  41304. },
  41305. set: function (value) {
  41306. if (StandardMaterial._BumpTextureEnabled === value) {
  41307. return;
  41308. }
  41309. StandardMaterial._BumpTextureEnabled = value;
  41310. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41311. },
  41312. enumerable: true,
  41313. configurable: true
  41314. });
  41315. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  41316. get: function () {
  41317. return StandardMaterial._LightmapTextureEnabled;
  41318. },
  41319. set: function (value) {
  41320. if (StandardMaterial._LightmapTextureEnabled === value) {
  41321. return;
  41322. }
  41323. StandardMaterial._LightmapTextureEnabled = value;
  41324. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41325. },
  41326. enumerable: true,
  41327. configurable: true
  41328. });
  41329. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  41330. get: function () {
  41331. return StandardMaterial._RefractionTextureEnabled;
  41332. },
  41333. set: function (value) {
  41334. if (StandardMaterial._RefractionTextureEnabled === value) {
  41335. return;
  41336. }
  41337. StandardMaterial._RefractionTextureEnabled = value;
  41338. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41339. },
  41340. enumerable: true,
  41341. configurable: true
  41342. });
  41343. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  41344. get: function () {
  41345. return StandardMaterial._ColorGradingTextureEnabled;
  41346. },
  41347. set: function (value) {
  41348. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  41349. return;
  41350. }
  41351. StandardMaterial._ColorGradingTextureEnabled = value;
  41352. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  41353. },
  41354. enumerable: true,
  41355. configurable: true
  41356. });
  41357. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  41358. get: function () {
  41359. return StandardMaterial._FresnelEnabled;
  41360. },
  41361. set: function (value) {
  41362. if (StandardMaterial._FresnelEnabled === value) {
  41363. return;
  41364. }
  41365. StandardMaterial._FresnelEnabled = value;
  41366. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  41367. },
  41368. enumerable: true,
  41369. configurable: true
  41370. });
  41371. return StandardMaterial;
  41372. }(BABYLON.PushMaterial));
  41373. // Flags used to enable or disable a type of texture for all Standard Materials
  41374. StandardMaterial._DiffuseTextureEnabled = true;
  41375. StandardMaterial._AmbientTextureEnabled = true;
  41376. StandardMaterial._OpacityTextureEnabled = true;
  41377. StandardMaterial._ReflectionTextureEnabled = true;
  41378. StandardMaterial._EmissiveTextureEnabled = true;
  41379. StandardMaterial._SpecularTextureEnabled = true;
  41380. StandardMaterial._BumpTextureEnabled = true;
  41381. StandardMaterial._LightmapTextureEnabled = true;
  41382. StandardMaterial._RefractionTextureEnabled = true;
  41383. StandardMaterial._ColorGradingTextureEnabled = true;
  41384. StandardMaterial._FresnelEnabled = true;
  41385. __decorate([
  41386. BABYLON.serializeAsTexture("diffuseTexture")
  41387. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  41388. __decorate([
  41389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41390. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  41391. __decorate([
  41392. BABYLON.serializeAsTexture("ambientTexture")
  41393. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  41394. __decorate([
  41395. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41396. ], StandardMaterial.prototype, "ambientTexture", void 0);
  41397. __decorate([
  41398. BABYLON.serializeAsTexture("opacityTexture")
  41399. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  41400. __decorate([
  41401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41402. ], StandardMaterial.prototype, "opacityTexture", void 0);
  41403. __decorate([
  41404. BABYLON.serializeAsTexture("reflectionTexture")
  41405. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  41406. __decorate([
  41407. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41408. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  41409. __decorate([
  41410. BABYLON.serializeAsTexture("emissiveTexture")
  41411. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  41412. __decorate([
  41413. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41414. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  41415. __decorate([
  41416. BABYLON.serializeAsTexture("specularTexture")
  41417. ], StandardMaterial.prototype, "_specularTexture", void 0);
  41418. __decorate([
  41419. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41420. ], StandardMaterial.prototype, "specularTexture", void 0);
  41421. __decorate([
  41422. BABYLON.serializeAsTexture("bumpTexture")
  41423. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  41424. __decorate([
  41425. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41426. ], StandardMaterial.prototype, "bumpTexture", void 0);
  41427. __decorate([
  41428. BABYLON.serializeAsTexture("lightmapTexture")
  41429. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  41430. __decorate([
  41431. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41432. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  41433. __decorate([
  41434. BABYLON.serializeAsTexture("refractionTexture")
  41435. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  41436. __decorate([
  41437. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41438. ], StandardMaterial.prototype, "refractionTexture", void 0);
  41439. __decorate([
  41440. BABYLON.serializeAsColor3("ambient")
  41441. ], StandardMaterial.prototype, "ambientColor", void 0);
  41442. __decorate([
  41443. BABYLON.serializeAsColor3("diffuse")
  41444. ], StandardMaterial.prototype, "diffuseColor", void 0);
  41445. __decorate([
  41446. BABYLON.serializeAsColor3("specular")
  41447. ], StandardMaterial.prototype, "specularColor", void 0);
  41448. __decorate([
  41449. BABYLON.serializeAsColor3("emissive")
  41450. ], StandardMaterial.prototype, "emissiveColor", void 0);
  41451. __decorate([
  41452. BABYLON.serialize()
  41453. ], StandardMaterial.prototype, "specularPower", void 0);
  41454. __decorate([
  41455. BABYLON.serialize("useAlphaFromDiffuseTexture")
  41456. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  41457. __decorate([
  41458. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41459. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  41460. __decorate([
  41461. BABYLON.serialize("useEmissiveAsIllumination")
  41462. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  41463. __decorate([
  41464. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41465. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  41466. __decorate([
  41467. BABYLON.serialize("linkEmissiveWithDiffuse")
  41468. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  41469. __decorate([
  41470. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41471. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  41472. __decorate([
  41473. BABYLON.serialize("useSpecularOverAlpha")
  41474. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  41475. __decorate([
  41476. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41477. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  41478. __decorate([
  41479. BABYLON.serialize("useReflectionOverAlpha")
  41480. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  41481. __decorate([
  41482. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41483. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  41484. __decorate([
  41485. BABYLON.serialize("disableLighting")
  41486. ], StandardMaterial.prototype, "_disableLighting", void 0);
  41487. __decorate([
  41488. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41489. ], StandardMaterial.prototype, "disableLighting", void 0);
  41490. __decorate([
  41491. BABYLON.serialize("useParallax")
  41492. ], StandardMaterial.prototype, "_useParallax", void 0);
  41493. __decorate([
  41494. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41495. ], StandardMaterial.prototype, "useParallax", void 0);
  41496. __decorate([
  41497. BABYLON.serialize("useParallaxOcclusion")
  41498. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  41499. __decorate([
  41500. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41501. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  41502. __decorate([
  41503. BABYLON.serialize()
  41504. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  41505. __decorate([
  41506. BABYLON.serialize("roughness")
  41507. ], StandardMaterial.prototype, "_roughness", void 0);
  41508. __decorate([
  41509. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41510. ], StandardMaterial.prototype, "roughness", void 0);
  41511. __decorate([
  41512. BABYLON.serialize()
  41513. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  41514. __decorate([
  41515. BABYLON.serialize()
  41516. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  41517. __decorate([
  41518. BABYLON.serialize("useLightmapAsShadowmap")
  41519. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  41520. __decorate([
  41521. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41522. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41523. __decorate([
  41524. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  41525. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  41526. __decorate([
  41527. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  41528. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  41529. __decorate([
  41530. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  41531. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  41532. __decorate([
  41533. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  41534. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  41535. __decorate([
  41536. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  41537. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  41538. __decorate([
  41539. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  41540. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  41541. __decorate([
  41542. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  41543. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  41544. __decorate([
  41545. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  41546. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  41547. __decorate([
  41548. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  41549. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  41550. __decorate([
  41551. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  41552. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  41553. __decorate([
  41554. BABYLON.serialize("useReflectionFresnelFromSpecular")
  41555. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  41556. __decorate([
  41557. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  41558. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  41559. __decorate([
  41560. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  41561. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  41562. __decorate([
  41563. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41564. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  41565. __decorate([
  41566. BABYLON.serialize("maxSimultaneousLights")
  41567. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  41568. __decorate([
  41569. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41570. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  41571. __decorate([
  41572. BABYLON.serialize("invertNormalMapX")
  41573. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  41574. __decorate([
  41575. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41576. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  41577. __decorate([
  41578. BABYLON.serialize("invertNormalMapY")
  41579. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  41580. __decorate([
  41581. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41582. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  41583. __decorate([
  41584. BABYLON.serialize("twoSidedLighting")
  41585. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  41586. __decorate([
  41587. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41588. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  41589. __decorate([
  41590. BABYLON.serializeAsTexture("cameraColorGradingTexture")
  41591. ], StandardMaterial.prototype, "_cameraColorGradingTexture", void 0);
  41592. __decorate([
  41593. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41594. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  41595. __decorate([
  41596. BABYLON.serializeAsColorCurves("cameraColorCurves")
  41597. ], StandardMaterial.prototype, "_cameraColorCurves", void 0);
  41598. __decorate([
  41599. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41600. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  41601. __decorate([
  41602. BABYLON.serialize()
  41603. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  41604. BABYLON.StandardMaterial = StandardMaterial;
  41605. })(BABYLON || (BABYLON = {}));
  41606. //# sourceMappingURL=babylon.standardMaterial.js.map
  41607. var BABYLON;
  41608. (function (BABYLON) {
  41609. /**
  41610. * This class implement a typical dictionary using a string as key and the generic type T as value.
  41611. * The underlying implementation relies on an associative array to ensure the best performances.
  41612. * The value can be anything including 'null' but except 'undefined'
  41613. */
  41614. var StringDictionary = (function () {
  41615. function StringDictionary() {
  41616. this._count = 0;
  41617. this._data = {};
  41618. }
  41619. /**
  41620. * This will clear this dictionary and copy the content from the 'source' one.
  41621. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  41622. * @param source the dictionary to take the content from and copy to this dictionary
  41623. */
  41624. StringDictionary.prototype.copyFrom = function (source) {
  41625. var _this = this;
  41626. this.clear();
  41627. source.forEach(function (t, v) { return _this.add(t, v); });
  41628. };
  41629. /**
  41630. * Get a value based from its key
  41631. * @param key the given key to get the matching value from
  41632. * @return the value if found, otherwise undefined is returned
  41633. */
  41634. StringDictionary.prototype.get = function (key) {
  41635. var val = this._data[key];
  41636. if (val !== undefined) {
  41637. return val;
  41638. }
  41639. return undefined;
  41640. };
  41641. /**
  41642. * Get a value from its key or add it if it doesn't exist.
  41643. * This method will ensure you that a given key/data will be present in the dictionary.
  41644. * @param key the given key to get the matching value from
  41645. * @param factory the factory that will create the value if the key is not present in the dictionary.
  41646. * The factory will only be invoked if there's no data for the given key.
  41647. * @return the value corresponding to the key.
  41648. */
  41649. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  41650. var val = this.get(key);
  41651. if (val !== undefined) {
  41652. return val;
  41653. }
  41654. val = factory(key);
  41655. if (val) {
  41656. this.add(key, val);
  41657. }
  41658. return val;
  41659. };
  41660. /**
  41661. * Get a value from its key if present in the dictionary otherwise add it
  41662. * @param key the key to get the value from
  41663. * @param val if there's no such key/value pair in the dictionary add it with this value
  41664. * @return the value corresponding to the key
  41665. */
  41666. StringDictionary.prototype.getOrAdd = function (key, val) {
  41667. var curVal = this.get(key);
  41668. if (curVal !== undefined) {
  41669. return curVal;
  41670. }
  41671. this.add(key, val);
  41672. return val;
  41673. };
  41674. /**
  41675. * Check if there's a given key in the dictionary
  41676. * @param key the key to check for
  41677. * @return true if the key is present, false otherwise
  41678. */
  41679. StringDictionary.prototype.contains = function (key) {
  41680. return this._data[key] !== undefined;
  41681. };
  41682. /**
  41683. * Add a new key and its corresponding value
  41684. * @param key the key to add
  41685. * @param value the value corresponding to the key
  41686. * @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
  41687. */
  41688. StringDictionary.prototype.add = function (key, value) {
  41689. if (this._data[key] !== undefined) {
  41690. return false;
  41691. }
  41692. this._data[key] = value;
  41693. ++this._count;
  41694. return true;
  41695. };
  41696. StringDictionary.prototype.set = function (key, value) {
  41697. if (this._data[key] === undefined) {
  41698. return false;
  41699. }
  41700. this._data[key] = value;
  41701. return true;
  41702. };
  41703. /**
  41704. * Get the element of the given key and remove it from the dictionary
  41705. * @param key
  41706. */
  41707. StringDictionary.prototype.getAndRemove = function (key) {
  41708. var val = this.get(key);
  41709. if (val !== undefined) {
  41710. delete this._data[key];
  41711. --this._count;
  41712. return val;
  41713. }
  41714. return null;
  41715. };
  41716. /**
  41717. * Remove a key/value from the dictionary.
  41718. * @param key the key to remove
  41719. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  41720. */
  41721. StringDictionary.prototype.remove = function (key) {
  41722. if (this.contains(key)) {
  41723. delete this._data[key];
  41724. --this._count;
  41725. return true;
  41726. }
  41727. return false;
  41728. };
  41729. /**
  41730. * Clear the whole content of the dictionary
  41731. */
  41732. StringDictionary.prototype.clear = function () {
  41733. this._data = {};
  41734. this._count = 0;
  41735. };
  41736. Object.defineProperty(StringDictionary.prototype, "count", {
  41737. get: function () {
  41738. return this._count;
  41739. },
  41740. enumerable: true,
  41741. configurable: true
  41742. });
  41743. /**
  41744. * Execute a callback on each key/val of the dictionary.
  41745. * Note that you can remove any element in this dictionary in the callback implementation
  41746. * @param callback the callback to execute on a given key/value pair
  41747. */
  41748. StringDictionary.prototype.forEach = function (callback) {
  41749. for (var cur in this._data) {
  41750. var val = this._data[cur];
  41751. callback(cur, val);
  41752. }
  41753. };
  41754. /**
  41755. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  41756. * If the callback returns null or undefined the method will iterate to the next key/value pair
  41757. * Note that you can remove any element in this dictionary in the callback implementation
  41758. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  41759. */
  41760. StringDictionary.prototype.first = function (callback) {
  41761. for (var cur in this._data) {
  41762. var val = this._data[cur];
  41763. var res = callback(cur, val);
  41764. if (res) {
  41765. return res;
  41766. }
  41767. }
  41768. return null;
  41769. };
  41770. return StringDictionary;
  41771. }());
  41772. BABYLON.StringDictionary = StringDictionary;
  41773. })(BABYLON || (BABYLON = {}));
  41774. //# sourceMappingURL=babylon.stringDictionary.js.map
  41775. var BABYLON;
  41776. (function (BABYLON) {
  41777. var DynamicFloatArrayElementInfo = (function () {
  41778. function DynamicFloatArrayElementInfo() {
  41779. }
  41780. return DynamicFloatArrayElementInfo;
  41781. }());
  41782. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  41783. /**
  41784. * 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.
  41785. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  41786. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  41787. * 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.
  41788. * 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.
  41789. * 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".
  41790. */
  41791. var DynamicFloatArray = (function () {
  41792. /**
  41793. * Construct an instance of the dynamic float array
  41794. * @param stride size of one element in float (i.e. not bytes!)
  41795. * @param initialElementCount the number of available entries at construction
  41796. */
  41797. function DynamicFloatArray(stride, initialElementCount) {
  41798. this.compareValueOffset = null;
  41799. this.sortingAscending = true;
  41800. this._stride = stride;
  41801. this.buffer = new Float32Array(stride * initialElementCount);
  41802. this._lastUsed = 0;
  41803. this._firstFree = 0;
  41804. this._allEntries = new Array(initialElementCount);
  41805. this._freeEntries = new Array(initialElementCount);
  41806. for (var i = 0; i < initialElementCount; i++) {
  41807. var element = new DynamicFloatArrayElementInfo();
  41808. element.offset = i * stride;
  41809. this._allEntries[i] = element;
  41810. this._freeEntries[initialElementCount - i - 1] = element;
  41811. }
  41812. }
  41813. /**
  41814. * Allocate an element in the array.
  41815. * @return the element info instance that contains the offset into the main buffer of the element's location.
  41816. * Beware, this offset may change when you call pack()
  41817. */
  41818. DynamicFloatArray.prototype.allocElement = function () {
  41819. if (this._freeEntries.length === 0) {
  41820. this._growBuffer();
  41821. }
  41822. var el = this._freeEntries.pop();
  41823. this._lastUsed = Math.max(el.offset, this._lastUsed);
  41824. if (el.offset === this._firstFree) {
  41825. if (this._freeEntries.length > 0) {
  41826. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  41827. }
  41828. else {
  41829. this._firstFree += this._stride;
  41830. }
  41831. }
  41832. return el;
  41833. };
  41834. /**
  41835. * Free the element corresponding to the given element info
  41836. * @param elInfo the element that describe the allocated element
  41837. */
  41838. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  41839. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  41840. this._freeEntries.push(elInfo);
  41841. };
  41842. /**
  41843. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  41844. * 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().
  41845. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  41846. */
  41847. DynamicFloatArray.prototype.pack = function () {
  41848. // no free slot? no need to pack
  41849. if (this._freeEntries.length === 0) {
  41850. return this.buffer;
  41851. }
  41852. // If the buffer is already packed the last used will always be lower than the first free
  41853. // 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.
  41854. if (this._lastUsed < this._firstFree) {
  41855. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  41856. return elementsBuffer_1;
  41857. }
  41858. var s = this._stride;
  41859. // 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
  41860. var lastFree = new DynamicFloatArrayElementInfo();
  41861. lastFree.offset = this.totalElementCount * s;
  41862. this._freeEntries.push(lastFree);
  41863. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  41864. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  41865. var firstFreeSlotOffset = sortedFree[0].offset;
  41866. var freeZoneSize = 1;
  41867. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  41868. var prevOffset = sortedFree[0].offset;
  41869. for (var i = 1; i < sortedFree.length; i++) {
  41870. // 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
  41871. if (firstFreeSlotOffset >= occupiedZoneSize) {
  41872. break;
  41873. }
  41874. var curFree = sortedFree[i];
  41875. var curOffset = curFree.offset;
  41876. // Compute the distance between this offset and the previous
  41877. var distance = curOffset - prevOffset;
  41878. // If the distance is the stride size, they are adjacent, it good, move to the next
  41879. if (distance === s) {
  41880. // Free zone is one element bigger
  41881. ++freeZoneSize;
  41882. // as we're about to iterate to the next, the cur becomes the previous...
  41883. prevOffset = curOffset;
  41884. continue;
  41885. }
  41886. // Distance is bigger, which means there's x element between the previous free and this one
  41887. var usedRange = (distance / s) - 1;
  41888. // Two cases the free zone is smaller than the data to move or bigger
  41889. // Copy what can fit in the free zone
  41890. var curMoveOffset = curOffset - s;
  41891. var copyCount = Math.min(freeZoneSize, usedRange);
  41892. for (var j = 0; j < copyCount; j++) {
  41893. var freeI = firstFreeSlotOffset / s;
  41894. var curI = curMoveOffset / s;
  41895. var moveEl = sortedAll[curI];
  41896. this._moveElement(moveEl, firstFreeSlotOffset);
  41897. var replacedEl = sortedAll[freeI];
  41898. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  41899. replacedEl.offset = curMoveOffset;
  41900. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  41901. sortedAll[freeI] = moveEl;
  41902. sortedAll[curI] = replacedEl;
  41903. curMoveOffset -= s;
  41904. firstFreeSlotOffset += s;
  41905. }
  41906. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  41907. if (freeZoneSize <= usedRange) {
  41908. firstFreeSlotOffset = curMoveOffset + s;
  41909. freeZoneSize = 1 + copyCount;
  41910. }
  41911. else {
  41912. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  41913. }
  41914. // as we're about to iterate to the next, the cur becomes the previous...
  41915. prevOffset = curOffset;
  41916. }
  41917. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  41918. this._lastUsed = firstFreeSlotOffset - s;
  41919. this._firstFree = firstFreeSlotOffset;
  41920. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  41921. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  41922. this._allEntries = sortedAll;
  41923. return elementsBuffer;
  41924. };
  41925. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  41926. for (var i = 0; i < this._stride; i++) {
  41927. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  41928. }
  41929. element.offset = destOffset;
  41930. };
  41931. DynamicFloatArray.prototype._growBuffer = function () {
  41932. // Allocate the new buffer with 50% more entries, copy the content of the current one
  41933. var newElCount = Math.floor(this.totalElementCount * 1.5);
  41934. var newBuffer = new Float32Array(newElCount * this._stride);
  41935. newBuffer.set(this.buffer);
  41936. var curCount = this.totalElementCount;
  41937. var addedCount = newElCount - this.totalElementCount;
  41938. for (var i = 0; i < addedCount; i++) {
  41939. var element = new DynamicFloatArrayElementInfo();
  41940. element.offset = (curCount + i) * this.stride;
  41941. this._allEntries.push(element);
  41942. this._freeEntries[addedCount - i - 1] = element;
  41943. }
  41944. this._firstFree = curCount * this.stride;
  41945. this.buffer = newBuffer;
  41946. };
  41947. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  41948. /**
  41949. * Get the total count of entries that can fit in the current buffer
  41950. * @returns the elements count
  41951. */
  41952. get: function () {
  41953. return this._allEntries.length;
  41954. },
  41955. enumerable: true,
  41956. configurable: true
  41957. });
  41958. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  41959. /**
  41960. * Get the count of free entries that can still be allocated without resizing the buffer
  41961. * @returns the free elements count
  41962. */
  41963. get: function () {
  41964. return this._freeEntries.length;
  41965. },
  41966. enumerable: true,
  41967. configurable: true
  41968. });
  41969. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  41970. /**
  41971. * Get the count of allocated elements
  41972. * @returns the allocated elements count
  41973. */
  41974. get: function () {
  41975. return this._allEntries.length - this._freeEntries.length;
  41976. },
  41977. enumerable: true,
  41978. configurable: true
  41979. });
  41980. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  41981. /**
  41982. * Return the size of one element in float
  41983. * @returns the size in float
  41984. */
  41985. get: function () {
  41986. return this._stride;
  41987. },
  41988. enumerable: true,
  41989. configurable: true
  41990. });
  41991. DynamicFloatArray.prototype.sort = function () {
  41992. var _this = this;
  41993. if (!this.compareValueOffset) {
  41994. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  41995. }
  41996. var count = this.usedElementCount;
  41997. // Do we have to (re)create the sort table?
  41998. if (!this._sortTable || this._sortTable.length < count) {
  41999. // 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...
  42000. var newCount = Math.min(this.totalElementCount, count * 2);
  42001. this._sortTable = new Array(newCount);
  42002. }
  42003. if (!this._sortedTable || this._sortedTable.length !== count) {
  42004. this._sortedTable = new Array(count);
  42005. }
  42006. // Because, you know...
  42007. this.pack();
  42008. //let stride = this.stride;
  42009. //for (let i = 0; i < count; i++) {
  42010. // let si = this._sortTable[i];
  42011. // if (!si) {
  42012. // si = new SortInfo();
  42013. // this._sortTable[i] = si;
  42014. // }
  42015. // si.entry = this._allEntries[i];
  42016. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  42017. // si.swapedOffset = null;
  42018. // this._sortedTable[i] = si;
  42019. //}
  42020. var curOffset = 0;
  42021. var stride = this.stride;
  42022. for (var i = 0; i < count; i++, curOffset += stride) {
  42023. var si = this._sortTable[i];
  42024. if (!si) {
  42025. si = new SortInfo();
  42026. this._sortTable[i] = si;
  42027. }
  42028. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  42029. si.offset = curOffset;
  42030. si.swapedOffset = null;
  42031. this._sortedTable[i] = si;
  42032. }
  42033. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  42034. if (this.sortingAscending) {
  42035. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  42036. }
  42037. else {
  42038. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  42039. }
  42040. var swapElements = function (src, dst) {
  42041. for (var i = 0; i < stride; i++) {
  42042. var tps = _this.buffer[dst + i];
  42043. _this.buffer[dst + i] = _this.buffer[src + i];
  42044. _this.buffer[src + i] = tps;
  42045. }
  42046. };
  42047. // 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:
  42048. // 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),
  42049. // and I still want something with a good algorithm complexity.
  42050. // 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,
  42051. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  42052. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  42053. // 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
  42054. // until we find a SortInfo object without a swapedOffset which means we got the right location
  42055. // 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
  42056. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  42057. for (var i = 0; i < count; i++) {
  42058. // Get the element to move
  42059. var sourceSI = this._sortedTable[i];
  42060. var destSI = this._sortTable[i];
  42061. var sourceOff = sourceSI.offset;
  42062. // If the source changed location, find the new one
  42063. if (sourceSI.swapedOffset) {
  42064. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  42065. var curSI = sourceSI;
  42066. while (curSI.swapedOffset) {
  42067. curSI = this._sortTable[curSI.swapedOffset / stride];
  42068. }
  42069. // Finally get the right location
  42070. sourceOff = curSI.offset;
  42071. }
  42072. // Tag the element being replaced with its new location
  42073. destSI.swapedOffset = sourceOff;
  42074. // Swap elements (only if needed)
  42075. if (sourceOff !== destSI.offset) {
  42076. swapElements(sourceOff, destSI.offset);
  42077. }
  42078. // Update the offset in the corresponding DFAE
  42079. //sourceSI.entry.offset = destSI.entry.offset;
  42080. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  42081. }
  42082. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  42083. return true;
  42084. };
  42085. return DynamicFloatArray;
  42086. }());
  42087. BABYLON.DynamicFloatArray = DynamicFloatArray;
  42088. var SortInfo = (function () {
  42089. function SortInfo() {
  42090. this.compareData = this.offset = this.swapedOffset = null;
  42091. }
  42092. return SortInfo;
  42093. }());
  42094. })(BABYLON || (BABYLON = {}));
  42095. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  42096. var BABYLON;
  42097. (function (BABYLON) {
  42098. var Condition = (function () {
  42099. function Condition(actionManager) {
  42100. this._actionManager = actionManager;
  42101. }
  42102. Condition.prototype.isValid = function () {
  42103. return true;
  42104. };
  42105. Condition.prototype._getProperty = function (propertyPath) {
  42106. return this._actionManager._getProperty(propertyPath);
  42107. };
  42108. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  42109. return this._actionManager._getEffectiveTarget(target, propertyPath);
  42110. };
  42111. Condition.prototype.serialize = function () {
  42112. };
  42113. Condition.prototype._serialize = function (serializedCondition) {
  42114. return {
  42115. type: 2,
  42116. children: [],
  42117. name: serializedCondition.name,
  42118. properties: serializedCondition.properties
  42119. };
  42120. };
  42121. return Condition;
  42122. }());
  42123. BABYLON.Condition = Condition;
  42124. var ValueCondition = (function (_super) {
  42125. __extends(ValueCondition, _super);
  42126. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  42127. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  42128. var _this = _super.call(this, actionManager) || this;
  42129. _this.propertyPath = propertyPath;
  42130. _this.value = value;
  42131. _this.operator = operator;
  42132. _this._target = target;
  42133. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  42134. _this._property = _this._getProperty(_this.propertyPath);
  42135. return _this;
  42136. }
  42137. Object.defineProperty(ValueCondition, "IsEqual", {
  42138. get: function () {
  42139. return ValueCondition._IsEqual;
  42140. },
  42141. enumerable: true,
  42142. configurable: true
  42143. });
  42144. Object.defineProperty(ValueCondition, "IsDifferent", {
  42145. get: function () {
  42146. return ValueCondition._IsDifferent;
  42147. },
  42148. enumerable: true,
  42149. configurable: true
  42150. });
  42151. Object.defineProperty(ValueCondition, "IsGreater", {
  42152. get: function () {
  42153. return ValueCondition._IsGreater;
  42154. },
  42155. enumerable: true,
  42156. configurable: true
  42157. });
  42158. Object.defineProperty(ValueCondition, "IsLesser", {
  42159. get: function () {
  42160. return ValueCondition._IsLesser;
  42161. },
  42162. enumerable: true,
  42163. configurable: true
  42164. });
  42165. // Methods
  42166. ValueCondition.prototype.isValid = function () {
  42167. switch (this.operator) {
  42168. case ValueCondition.IsGreater:
  42169. return this._effectiveTarget[this._property] > this.value;
  42170. case ValueCondition.IsLesser:
  42171. return this._effectiveTarget[this._property] < this.value;
  42172. case ValueCondition.IsEqual:
  42173. case ValueCondition.IsDifferent:
  42174. var check;
  42175. if (this.value.equals) {
  42176. check = this.value.equals(this._effectiveTarget[this._property]);
  42177. }
  42178. else {
  42179. check = this.value === this._effectiveTarget[this._property];
  42180. }
  42181. return this.operator === ValueCondition.IsEqual ? check : !check;
  42182. }
  42183. return false;
  42184. };
  42185. ValueCondition.prototype.serialize = function () {
  42186. return this._serialize({
  42187. name: "ValueCondition",
  42188. properties: [
  42189. BABYLON.Action._GetTargetProperty(this._target),
  42190. { name: "propertyPath", value: this.propertyPath },
  42191. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  42192. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  42193. ]
  42194. });
  42195. };
  42196. ValueCondition.GetOperatorName = function (operator) {
  42197. switch (operator) {
  42198. case ValueCondition._IsEqual: return "IsEqual";
  42199. case ValueCondition._IsDifferent: return "IsDifferent";
  42200. case ValueCondition._IsGreater: return "IsGreater";
  42201. case ValueCondition._IsLesser: return "IsLesser";
  42202. default: return "";
  42203. }
  42204. };
  42205. return ValueCondition;
  42206. }(Condition));
  42207. // Statics
  42208. ValueCondition._IsEqual = 0;
  42209. ValueCondition._IsDifferent = 1;
  42210. ValueCondition._IsGreater = 2;
  42211. ValueCondition._IsLesser = 3;
  42212. BABYLON.ValueCondition = ValueCondition;
  42213. var PredicateCondition = (function (_super) {
  42214. __extends(PredicateCondition, _super);
  42215. function PredicateCondition(actionManager, predicate) {
  42216. var _this = _super.call(this, actionManager) || this;
  42217. _this.predicate = predicate;
  42218. return _this;
  42219. }
  42220. PredicateCondition.prototype.isValid = function () {
  42221. return this.predicate();
  42222. };
  42223. return PredicateCondition;
  42224. }(Condition));
  42225. BABYLON.PredicateCondition = PredicateCondition;
  42226. var StateCondition = (function (_super) {
  42227. __extends(StateCondition, _super);
  42228. function StateCondition(actionManager, target, value) {
  42229. var _this = _super.call(this, actionManager) || this;
  42230. _this.value = value;
  42231. _this._target = target;
  42232. return _this;
  42233. }
  42234. // Methods
  42235. StateCondition.prototype.isValid = function () {
  42236. return this._target.state === this.value;
  42237. };
  42238. StateCondition.prototype.serialize = function () {
  42239. return this._serialize({
  42240. name: "StateCondition",
  42241. properties: [
  42242. BABYLON.Action._GetTargetProperty(this._target),
  42243. { name: "value", value: this.value }
  42244. ]
  42245. });
  42246. };
  42247. return StateCondition;
  42248. }(Condition));
  42249. BABYLON.StateCondition = StateCondition;
  42250. })(BABYLON || (BABYLON = {}));
  42251. //# sourceMappingURL=babylon.condition.js.map
  42252. var BABYLON;
  42253. (function (BABYLON) {
  42254. var Action = (function () {
  42255. function Action(triggerOptions, condition) {
  42256. this.triggerOptions = triggerOptions;
  42257. if (triggerOptions.parameter) {
  42258. this.trigger = triggerOptions.trigger;
  42259. this._triggerParameter = triggerOptions.parameter;
  42260. }
  42261. else {
  42262. this.trigger = triggerOptions;
  42263. }
  42264. this._nextActiveAction = this;
  42265. this._condition = condition;
  42266. }
  42267. // Methods
  42268. Action.prototype._prepare = function () {
  42269. };
  42270. Action.prototype.getTriggerParameter = function () {
  42271. return this._triggerParameter;
  42272. };
  42273. Action.prototype._executeCurrent = function (evt) {
  42274. if (this._nextActiveAction._condition) {
  42275. var condition = this._nextActiveAction._condition;
  42276. var currentRenderId = this._actionManager.getScene().getRenderId();
  42277. // We cache the current evaluation for the current frame
  42278. if (condition._evaluationId === currentRenderId) {
  42279. if (!condition._currentResult) {
  42280. return;
  42281. }
  42282. }
  42283. else {
  42284. condition._evaluationId = currentRenderId;
  42285. if (!condition.isValid()) {
  42286. condition._currentResult = false;
  42287. return;
  42288. }
  42289. condition._currentResult = true;
  42290. }
  42291. }
  42292. this._nextActiveAction.execute(evt);
  42293. this.skipToNextActiveAction();
  42294. };
  42295. Action.prototype.execute = function (evt) {
  42296. };
  42297. Action.prototype.skipToNextActiveAction = function () {
  42298. if (this._nextActiveAction._child) {
  42299. if (!this._nextActiveAction._child._actionManager) {
  42300. this._nextActiveAction._child._actionManager = this._actionManager;
  42301. }
  42302. this._nextActiveAction = this._nextActiveAction._child;
  42303. }
  42304. else {
  42305. this._nextActiveAction = this;
  42306. }
  42307. };
  42308. Action.prototype.then = function (action) {
  42309. this._child = action;
  42310. action._actionManager = this._actionManager;
  42311. action._prepare();
  42312. return action;
  42313. };
  42314. Action.prototype._getProperty = function (propertyPath) {
  42315. return this._actionManager._getProperty(propertyPath);
  42316. };
  42317. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  42318. return this._actionManager._getEffectiveTarget(target, propertyPath);
  42319. };
  42320. Action.prototype.serialize = function (parent) {
  42321. };
  42322. // Called by BABYLON.Action objects in serialize(...). Internal use
  42323. Action.prototype._serialize = function (serializedAction, parent) {
  42324. var serializationObject = {
  42325. type: 1,
  42326. children: [],
  42327. name: serializedAction.name,
  42328. properties: serializedAction.properties || []
  42329. };
  42330. // Serialize child
  42331. if (this._child) {
  42332. this._child.serialize(serializationObject);
  42333. }
  42334. // Check if "this" has a condition
  42335. if (this._condition) {
  42336. var serializedCondition = this._condition.serialize();
  42337. serializedCondition.children.push(serializationObject);
  42338. if (parent) {
  42339. parent.children.push(serializedCondition);
  42340. }
  42341. return serializedCondition;
  42342. }
  42343. if (parent) {
  42344. parent.children.push(serializationObject);
  42345. }
  42346. return serializationObject;
  42347. };
  42348. return Action;
  42349. }());
  42350. Action._SerializeValueAsString = function (value) {
  42351. if (typeof value === "number") {
  42352. return value.toString();
  42353. }
  42354. if (typeof value === "boolean") {
  42355. return value ? "true" : "false";
  42356. }
  42357. if (value instanceof BABYLON.Vector2) {
  42358. return value.x + ", " + value.y;
  42359. }
  42360. if (value instanceof BABYLON.Vector3) {
  42361. return value.x + ", " + value.y + ", " + value.z;
  42362. }
  42363. if (value instanceof BABYLON.Color3) {
  42364. return value.r + ", " + value.g + ", " + value.b;
  42365. }
  42366. if (value instanceof BABYLON.Color4) {
  42367. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  42368. }
  42369. return value; // string
  42370. };
  42371. Action._GetTargetProperty = function (target) {
  42372. return {
  42373. name: "target",
  42374. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  42375. : target instanceof BABYLON.Light ? "LightProperties"
  42376. : target instanceof BABYLON.Camera ? "CameraProperties"
  42377. : "SceneProperties",
  42378. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  42379. };
  42380. };
  42381. BABYLON.Action = Action;
  42382. })(BABYLON || (BABYLON = {}));
  42383. //# sourceMappingURL=babylon.action.js.map
  42384. var BABYLON;
  42385. (function (BABYLON) {
  42386. /**
  42387. * ActionEvent is the event beint sent when an action is triggered.
  42388. */
  42389. var ActionEvent = (function () {
  42390. /**
  42391. * @constructor
  42392. * @param source The mesh or sprite that triggered the action.
  42393. * @param pointerX The X mouse cursor position at the time of the event
  42394. * @param pointerY The Y mouse cursor position at the time of the event
  42395. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  42396. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  42397. */
  42398. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  42399. this.source = source;
  42400. this.pointerX = pointerX;
  42401. this.pointerY = pointerY;
  42402. this.meshUnderPointer = meshUnderPointer;
  42403. this.sourceEvent = sourceEvent;
  42404. this.additionalData = additionalData;
  42405. }
  42406. /**
  42407. * Helper function to auto-create an ActionEvent from a source mesh.
  42408. * @param source The source mesh that triggered the event
  42409. * @param evt {Event} The original (browser) event
  42410. */
  42411. ActionEvent.CreateNew = function (source, evt, additionalData) {
  42412. var scene = source.getScene();
  42413. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  42414. };
  42415. /**
  42416. * Helper function to auto-create an ActionEvent from a source mesh.
  42417. * @param source The source sprite that triggered the event
  42418. * @param scene Scene associated with the sprite
  42419. * @param evt {Event} The original (browser) event
  42420. */
  42421. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  42422. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  42423. };
  42424. /**
  42425. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  42426. * @param scene the scene where the event occurred
  42427. * @param evt {Event} The original (browser) event
  42428. */
  42429. ActionEvent.CreateNewFromScene = function (scene, evt) {
  42430. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  42431. };
  42432. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  42433. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  42434. };
  42435. return ActionEvent;
  42436. }());
  42437. BABYLON.ActionEvent = ActionEvent;
  42438. /**
  42439. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  42440. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  42441. */
  42442. var ActionManager = (function () {
  42443. function ActionManager(scene) {
  42444. // Members
  42445. this.actions = new Array();
  42446. this.hoverCursor = '';
  42447. this._scene = scene;
  42448. scene._actionManagers.push(this);
  42449. }
  42450. Object.defineProperty(ActionManager, "NothingTrigger", {
  42451. get: function () {
  42452. return ActionManager._NothingTrigger;
  42453. },
  42454. enumerable: true,
  42455. configurable: true
  42456. });
  42457. Object.defineProperty(ActionManager, "OnPickTrigger", {
  42458. get: function () {
  42459. return ActionManager._OnPickTrigger;
  42460. },
  42461. enumerable: true,
  42462. configurable: true
  42463. });
  42464. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  42465. get: function () {
  42466. return ActionManager._OnLeftPickTrigger;
  42467. },
  42468. enumerable: true,
  42469. configurable: true
  42470. });
  42471. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  42472. get: function () {
  42473. return ActionManager._OnRightPickTrigger;
  42474. },
  42475. enumerable: true,
  42476. configurable: true
  42477. });
  42478. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  42479. get: function () {
  42480. return ActionManager._OnCenterPickTrigger;
  42481. },
  42482. enumerable: true,
  42483. configurable: true
  42484. });
  42485. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  42486. get: function () {
  42487. return ActionManager._OnPickDownTrigger;
  42488. },
  42489. enumerable: true,
  42490. configurable: true
  42491. });
  42492. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  42493. get: function () {
  42494. return ActionManager._OnDoublePickTrigger;
  42495. },
  42496. enumerable: true,
  42497. configurable: true
  42498. });
  42499. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  42500. get: function () {
  42501. return ActionManager._OnPickUpTrigger;
  42502. },
  42503. enumerable: true,
  42504. configurable: true
  42505. });
  42506. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  42507. /// This trigger will only be raised if you also declared a OnPickDown
  42508. get: function () {
  42509. return ActionManager._OnPickOutTrigger;
  42510. },
  42511. enumerable: true,
  42512. configurable: true
  42513. });
  42514. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  42515. get: function () {
  42516. return ActionManager._OnLongPressTrigger;
  42517. },
  42518. enumerable: true,
  42519. configurable: true
  42520. });
  42521. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  42522. get: function () {
  42523. return ActionManager._OnPointerOverTrigger;
  42524. },
  42525. enumerable: true,
  42526. configurable: true
  42527. });
  42528. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  42529. get: function () {
  42530. return ActionManager._OnPointerOutTrigger;
  42531. },
  42532. enumerable: true,
  42533. configurable: true
  42534. });
  42535. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  42536. get: function () {
  42537. return ActionManager._OnEveryFrameTrigger;
  42538. },
  42539. enumerable: true,
  42540. configurable: true
  42541. });
  42542. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  42543. get: function () {
  42544. return ActionManager._OnIntersectionEnterTrigger;
  42545. },
  42546. enumerable: true,
  42547. configurable: true
  42548. });
  42549. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  42550. get: function () {
  42551. return ActionManager._OnIntersectionExitTrigger;
  42552. },
  42553. enumerable: true,
  42554. configurable: true
  42555. });
  42556. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  42557. get: function () {
  42558. return ActionManager._OnKeyDownTrigger;
  42559. },
  42560. enumerable: true,
  42561. configurable: true
  42562. });
  42563. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  42564. get: function () {
  42565. return ActionManager._OnKeyUpTrigger;
  42566. },
  42567. enumerable: true,
  42568. configurable: true
  42569. });
  42570. // Methods
  42571. ActionManager.prototype.dispose = function () {
  42572. var index = this._scene._actionManagers.indexOf(this);
  42573. for (var i = 0; i < this.actions.length; i++) {
  42574. var action = this.actions[i];
  42575. ActionManager.Triggers[action.trigger]--;
  42576. if (ActionManager.Triggers[action.trigger] === 0) {
  42577. delete ActionManager.Triggers[action.trigger];
  42578. }
  42579. }
  42580. if (index > -1) {
  42581. this._scene._actionManagers.splice(index, 1);
  42582. }
  42583. };
  42584. ActionManager.prototype.getScene = function () {
  42585. return this._scene;
  42586. };
  42587. /**
  42588. * Does this action manager handles actions of any of the given triggers
  42589. * @param {number[]} triggers - the triggers to be tested
  42590. * @return {boolean} whether one (or more) of the triggers is handeled
  42591. */
  42592. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  42593. for (var index = 0; index < this.actions.length; index++) {
  42594. var action = this.actions[index];
  42595. if (triggers.indexOf(action.trigger) > -1) {
  42596. return true;
  42597. }
  42598. }
  42599. return false;
  42600. };
  42601. /**
  42602. * Does this action manager handles actions of a given trigger
  42603. * @param {number} trigger - the trigger to be tested
  42604. * @return {boolean} whether the trigger is handeled
  42605. */
  42606. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  42607. for (var index = 0; index < this.actions.length; index++) {
  42608. var action = this.actions[index];
  42609. if (action.trigger === trigger) {
  42610. return true;
  42611. }
  42612. }
  42613. return false;
  42614. };
  42615. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  42616. /**
  42617. * Does this action manager has pointer triggers
  42618. * @return {boolean} whether or not it has pointer triggers
  42619. */
  42620. get: function () {
  42621. for (var index = 0; index < this.actions.length; index++) {
  42622. var action = this.actions[index];
  42623. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  42624. return true;
  42625. }
  42626. }
  42627. return false;
  42628. },
  42629. enumerable: true,
  42630. configurable: true
  42631. });
  42632. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  42633. /**
  42634. * Does this action manager has pick triggers
  42635. * @return {boolean} whether or not it has pick triggers
  42636. */
  42637. get: function () {
  42638. for (var index = 0; index < this.actions.length; index++) {
  42639. var action = this.actions[index];
  42640. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  42641. return true;
  42642. }
  42643. }
  42644. return false;
  42645. },
  42646. enumerable: true,
  42647. configurable: true
  42648. });
  42649. Object.defineProperty(ActionManager, "HasTriggers", {
  42650. /**
  42651. * Does exist one action manager with at least one trigger
  42652. * @return {boolean} whether or not it exists one action manager with one trigger
  42653. **/
  42654. get: function () {
  42655. for (var t in ActionManager.Triggers) {
  42656. if (ActionManager.Triggers.hasOwnProperty(t)) {
  42657. return true;
  42658. }
  42659. }
  42660. return false;
  42661. },
  42662. enumerable: true,
  42663. configurable: true
  42664. });
  42665. Object.defineProperty(ActionManager, "HasPickTriggers", {
  42666. /**
  42667. * Does exist one action manager with at least one pick trigger
  42668. * @return {boolean} whether or not it exists one action manager with one pick trigger
  42669. **/
  42670. get: function () {
  42671. for (var t in ActionManager.Triggers) {
  42672. if (ActionManager.Triggers.hasOwnProperty(t)) {
  42673. var t_int = parseInt(t);
  42674. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  42675. return true;
  42676. }
  42677. }
  42678. }
  42679. return false;
  42680. },
  42681. enumerable: true,
  42682. configurable: true
  42683. });
  42684. /**
  42685. * Does exist one action manager that handles actions of a given trigger
  42686. * @param {number} trigger - the trigger to be tested
  42687. * @return {boolean} whether the trigger is handeled by at least one action manager
  42688. **/
  42689. ActionManager.HasSpecificTrigger = function (trigger) {
  42690. for (var t in ActionManager.Triggers) {
  42691. if (ActionManager.Triggers.hasOwnProperty(t)) {
  42692. var t_int = parseInt(t);
  42693. if (t_int === trigger) {
  42694. return true;
  42695. }
  42696. }
  42697. }
  42698. return false;
  42699. };
  42700. /**
  42701. * Registers an action to this action manager
  42702. * @param {BABYLON.Action} action - the action to be registered
  42703. * @return {BABYLON.Action} the action amended (prepared) after registration
  42704. */
  42705. ActionManager.prototype.registerAction = function (action) {
  42706. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  42707. if (this.getScene().actionManager !== this) {
  42708. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  42709. return null;
  42710. }
  42711. }
  42712. this.actions.push(action);
  42713. if (ActionManager.Triggers[action.trigger]) {
  42714. ActionManager.Triggers[action.trigger]++;
  42715. }
  42716. else {
  42717. ActionManager.Triggers[action.trigger] = 1;
  42718. }
  42719. action._actionManager = this;
  42720. action._prepare();
  42721. return action;
  42722. };
  42723. /**
  42724. * Process a specific trigger
  42725. * @param {number} trigger - the trigger to process
  42726. * @param evt {BABYLON.ActionEvent} the event details to be processed
  42727. */
  42728. ActionManager.prototype.processTrigger = function (trigger, evt) {
  42729. for (var index = 0; index < this.actions.length; index++) {
  42730. var action = this.actions[index];
  42731. if (action.trigger === trigger) {
  42732. if (trigger === ActionManager.OnKeyUpTrigger
  42733. || trigger === ActionManager.OnKeyDownTrigger) {
  42734. var parameter = action.getTriggerParameter();
  42735. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  42736. if (!parameter.toLowerCase) {
  42737. continue;
  42738. }
  42739. var lowerCase = parameter.toLowerCase();
  42740. if (lowerCase !== evt.sourceEvent.key) {
  42741. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  42742. var actualkey = String.fromCharCode(unicode).toLowerCase();
  42743. if (actualkey !== lowerCase) {
  42744. continue;
  42745. }
  42746. }
  42747. }
  42748. }
  42749. action._executeCurrent(evt);
  42750. }
  42751. }
  42752. };
  42753. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  42754. var properties = propertyPath.split(".");
  42755. for (var index = 0; index < properties.length - 1; index++) {
  42756. target = target[properties[index]];
  42757. }
  42758. return target;
  42759. };
  42760. ActionManager.prototype._getProperty = function (propertyPath) {
  42761. var properties = propertyPath.split(".");
  42762. return properties[properties.length - 1];
  42763. };
  42764. ActionManager.prototype.serialize = function (name) {
  42765. var root = {
  42766. children: [],
  42767. name: name,
  42768. type: 3,
  42769. properties: [] // Empty for root but required
  42770. };
  42771. for (var i = 0; i < this.actions.length; i++) {
  42772. var triggerObject = {
  42773. type: 0,
  42774. children: [],
  42775. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  42776. properties: []
  42777. };
  42778. var triggerOptions = this.actions[i].triggerOptions;
  42779. if (triggerOptions && typeof triggerOptions !== "number") {
  42780. if (triggerOptions.parameter instanceof BABYLON.Node) {
  42781. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  42782. }
  42783. else {
  42784. var parameter = {};
  42785. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  42786. if (triggerOptions.parameter.mesh) {
  42787. parameter._meshId = triggerOptions.parameter.mesh.id;
  42788. }
  42789. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  42790. }
  42791. }
  42792. // Serialize child action, recursively
  42793. this.actions[i].serialize(triggerObject);
  42794. // Add serialized trigger
  42795. root.children.push(triggerObject);
  42796. }
  42797. return root;
  42798. };
  42799. ActionManager.Parse = function (parsedActions, object, scene) {
  42800. var actionManager = new BABYLON.ActionManager(scene);
  42801. if (object === null)
  42802. scene.actionManager = actionManager;
  42803. else
  42804. object.actionManager = actionManager;
  42805. // instanciate a new object
  42806. var instanciate = function (name, params) {
  42807. var newInstance = Object.create(BABYLON[name].prototype);
  42808. newInstance.constructor.apply(newInstance, params);
  42809. return newInstance;
  42810. };
  42811. var parseParameter = function (name, value, target, propertyPath) {
  42812. if (propertyPath === null) {
  42813. // String, boolean or float
  42814. var floatValue = parseFloat(value);
  42815. if (value === "true" || value === "false")
  42816. return value === "true";
  42817. else
  42818. return isNaN(floatValue) ? value : floatValue;
  42819. }
  42820. var effectiveTarget = propertyPath.split(".");
  42821. var values = value.split(",");
  42822. // Get effective Target
  42823. for (var i = 0; i < effectiveTarget.length; i++) {
  42824. target = target[effectiveTarget[i]];
  42825. }
  42826. // Return appropriate value with its type
  42827. if (typeof (target) === "boolean")
  42828. return values[0] === "true";
  42829. if (typeof (target) === "string")
  42830. return values[0];
  42831. // Parameters with multiple values such as Vector3 etc.
  42832. var split = new Array();
  42833. for (var i = 0; i < values.length; i++)
  42834. split.push(parseFloat(values[i]));
  42835. if (target instanceof BABYLON.Vector3)
  42836. return BABYLON.Vector3.FromArray(split);
  42837. if (target instanceof BABYLON.Vector4)
  42838. return BABYLON.Vector4.FromArray(split);
  42839. if (target instanceof BABYLON.Color3)
  42840. return BABYLON.Color3.FromArray(split);
  42841. if (target instanceof BABYLON.Color4)
  42842. return BABYLON.Color4.FromArray(split);
  42843. return parseFloat(values[0]);
  42844. };
  42845. // traverse graph per trigger
  42846. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  42847. if (combineArray === void 0) { combineArray = null; }
  42848. if (parsedAction.detached)
  42849. return;
  42850. var parameters = new Array();
  42851. var target = null;
  42852. var propertyPath = null;
  42853. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  42854. // Parameters
  42855. if (parsedAction.type === 2)
  42856. parameters.push(actionManager);
  42857. else
  42858. parameters.push(trigger);
  42859. if (combine) {
  42860. var actions = new Array();
  42861. for (var j = 0; j < parsedAction.combine.length; j++) {
  42862. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  42863. }
  42864. parameters.push(actions);
  42865. }
  42866. else {
  42867. for (var i = 0; i < parsedAction.properties.length; i++) {
  42868. var value = parsedAction.properties[i].value;
  42869. var name = parsedAction.properties[i].name;
  42870. var targetType = parsedAction.properties[i].targetType;
  42871. if (name === "target")
  42872. if (targetType !== null && targetType === "SceneProperties")
  42873. value = target = scene;
  42874. else
  42875. value = target = scene.getNodeByName(value);
  42876. else if (name === "parent")
  42877. value = scene.getNodeByName(value);
  42878. else if (name === "sound")
  42879. value = scene.getSoundByName(value);
  42880. else if (name !== "propertyPath") {
  42881. if (parsedAction.type === 2 && name === "operator")
  42882. value = BABYLON.ValueCondition[value];
  42883. else
  42884. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  42885. }
  42886. else {
  42887. propertyPath = value;
  42888. }
  42889. parameters.push(value);
  42890. }
  42891. }
  42892. if (combineArray === null) {
  42893. parameters.push(condition);
  42894. }
  42895. else {
  42896. parameters.push(null);
  42897. }
  42898. // If interpolate value action
  42899. if (parsedAction.name === "InterpolateValueAction") {
  42900. var param = parameters[parameters.length - 2];
  42901. parameters[parameters.length - 1] = param;
  42902. parameters[parameters.length - 2] = condition;
  42903. }
  42904. // Action or condition(s) and not CombineAction
  42905. var newAction = instanciate(parsedAction.name, parameters);
  42906. if (newAction instanceof BABYLON.Condition && condition !== null) {
  42907. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  42908. if (action)
  42909. action.then(nothing);
  42910. else
  42911. actionManager.registerAction(nothing);
  42912. action = nothing;
  42913. }
  42914. if (combineArray === null) {
  42915. if (newAction instanceof BABYLON.Condition) {
  42916. condition = newAction;
  42917. newAction = action;
  42918. }
  42919. else {
  42920. condition = null;
  42921. if (action)
  42922. action.then(newAction);
  42923. else
  42924. actionManager.registerAction(newAction);
  42925. }
  42926. }
  42927. else {
  42928. combineArray.push(newAction);
  42929. }
  42930. for (var i = 0; i < parsedAction.children.length; i++)
  42931. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  42932. };
  42933. // triggers
  42934. for (var i = 0; i < parsedActions.children.length; i++) {
  42935. var triggerParams;
  42936. var trigger = parsedActions.children[i];
  42937. if (trigger.properties.length > 0) {
  42938. var param = trigger.properties[0].value;
  42939. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  42940. if (value._meshId) {
  42941. value.mesh = scene.getMeshByID(value._meshId);
  42942. }
  42943. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  42944. }
  42945. else
  42946. triggerParams = BABYLON.ActionManager[trigger.name];
  42947. for (var j = 0; j < trigger.children.length; j++) {
  42948. if (!trigger.detached)
  42949. traverse(trigger.children[j], triggerParams, null, null);
  42950. }
  42951. }
  42952. };
  42953. ActionManager.GetTriggerName = function (trigger) {
  42954. switch (trigger) {
  42955. case 0: return "NothingTrigger";
  42956. case 1: return "OnPickTrigger";
  42957. case 2: return "OnLeftPickTrigger";
  42958. case 3: return "OnRightPickTrigger";
  42959. case 4: return "OnCenterPickTrigger";
  42960. case 5: return "OnPickDownTrigger";
  42961. case 6: return "OnPickUpTrigger";
  42962. case 7: return "OnLongPressTrigger";
  42963. case 8: return "OnPointerOverTrigger";
  42964. case 9: return "OnPointerOutTrigger";
  42965. case 10: return "OnEveryFrameTrigger";
  42966. case 11: return "OnIntersectionEnterTrigger";
  42967. case 12: return "OnIntersectionExitTrigger";
  42968. case 13: return "OnKeyDownTrigger";
  42969. case 14: return "OnKeyUpTrigger";
  42970. case 15: return "OnPickOutTrigger";
  42971. default: return "";
  42972. }
  42973. };
  42974. return ActionManager;
  42975. }());
  42976. // Statics
  42977. ActionManager._NothingTrigger = 0;
  42978. ActionManager._OnPickTrigger = 1;
  42979. ActionManager._OnLeftPickTrigger = 2;
  42980. ActionManager._OnRightPickTrigger = 3;
  42981. ActionManager._OnCenterPickTrigger = 4;
  42982. ActionManager._OnPickDownTrigger = 5;
  42983. ActionManager._OnDoublePickTrigger = 6;
  42984. ActionManager._OnPickUpTrigger = 7;
  42985. ActionManager._OnLongPressTrigger = 8;
  42986. ActionManager._OnPointerOverTrigger = 9;
  42987. ActionManager._OnPointerOutTrigger = 10;
  42988. ActionManager._OnEveryFrameTrigger = 11;
  42989. ActionManager._OnIntersectionEnterTrigger = 12;
  42990. ActionManager._OnIntersectionExitTrigger = 13;
  42991. ActionManager._OnKeyDownTrigger = 14;
  42992. ActionManager._OnKeyUpTrigger = 15;
  42993. ActionManager._OnPickOutTrigger = 16;
  42994. ActionManager.Triggers = {};
  42995. BABYLON.ActionManager = ActionManager;
  42996. })(BABYLON || (BABYLON = {}));
  42997. //# sourceMappingURL=babylon.actionManager.js.map
  42998. var BABYLON;
  42999. (function (BABYLON) {
  43000. var InterpolateValueAction = (function (_super) {
  43001. __extends(InterpolateValueAction, _super);
  43002. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  43003. if (duration === void 0) { duration = 1000; }
  43004. var _this = _super.call(this, triggerOptions, condition) || this;
  43005. _this.propertyPath = propertyPath;
  43006. _this.value = value;
  43007. _this.duration = duration;
  43008. _this.stopOtherAnimations = stopOtherAnimations;
  43009. _this.onInterpolationDone = onInterpolationDone;
  43010. _this._target = _this._effectiveTarget = target;
  43011. return _this;
  43012. }
  43013. InterpolateValueAction.prototype._prepare = function () {
  43014. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  43015. this._property = this._getProperty(this.propertyPath);
  43016. };
  43017. InterpolateValueAction.prototype.execute = function () {
  43018. var scene = this._actionManager.getScene();
  43019. var keys = [
  43020. {
  43021. frame: 0,
  43022. value: this._effectiveTarget[this._property]
  43023. }, {
  43024. frame: 100,
  43025. value: this.value
  43026. }
  43027. ];
  43028. var dataType;
  43029. if (typeof this.value === "number") {
  43030. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  43031. }
  43032. else if (this.value instanceof BABYLON.Color3) {
  43033. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  43034. }
  43035. else if (this.value instanceof BABYLON.Vector3) {
  43036. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  43037. }
  43038. else if (this.value instanceof BABYLON.Matrix) {
  43039. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  43040. }
  43041. else if (this.value instanceof BABYLON.Quaternion) {
  43042. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  43043. }
  43044. else {
  43045. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  43046. return;
  43047. }
  43048. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  43049. animation.setKeys(keys);
  43050. if (this.stopOtherAnimations) {
  43051. scene.stopAnimation(this._effectiveTarget);
  43052. }
  43053. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  43054. };
  43055. InterpolateValueAction.prototype.serialize = function (parent) {
  43056. return _super.prototype._serialize.call(this, {
  43057. name: "InterpolateValueAction",
  43058. properties: [
  43059. BABYLON.Action._GetTargetProperty(this._target),
  43060. { name: "propertyPath", value: this.propertyPath },
  43061. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  43062. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  43063. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  43064. ]
  43065. }, parent);
  43066. };
  43067. return InterpolateValueAction;
  43068. }(BABYLON.Action));
  43069. BABYLON.InterpolateValueAction = InterpolateValueAction;
  43070. })(BABYLON || (BABYLON = {}));
  43071. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  43072. var BABYLON;
  43073. (function (BABYLON) {
  43074. var SwitchBooleanAction = (function (_super) {
  43075. __extends(SwitchBooleanAction, _super);
  43076. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  43077. var _this = _super.call(this, triggerOptions, condition) || this;
  43078. _this.propertyPath = propertyPath;
  43079. _this._target = _this._effectiveTarget = target;
  43080. return _this;
  43081. }
  43082. SwitchBooleanAction.prototype._prepare = function () {
  43083. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  43084. this._property = this._getProperty(this.propertyPath);
  43085. };
  43086. SwitchBooleanAction.prototype.execute = function () {
  43087. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  43088. };
  43089. SwitchBooleanAction.prototype.serialize = function (parent) {
  43090. return _super.prototype._serialize.call(this, {
  43091. name: "SwitchBooleanAction",
  43092. properties: [
  43093. BABYLON.Action._GetTargetProperty(this._target),
  43094. { name: "propertyPath", value: this.propertyPath }
  43095. ]
  43096. }, parent);
  43097. };
  43098. return SwitchBooleanAction;
  43099. }(BABYLON.Action));
  43100. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  43101. var SetStateAction = (function (_super) {
  43102. __extends(SetStateAction, _super);
  43103. function SetStateAction(triggerOptions, target, value, condition) {
  43104. var _this = _super.call(this, triggerOptions, condition) || this;
  43105. _this.value = value;
  43106. _this._target = target;
  43107. return _this;
  43108. }
  43109. SetStateAction.prototype.execute = function () {
  43110. this._target.state = this.value;
  43111. };
  43112. SetStateAction.prototype.serialize = function (parent) {
  43113. return _super.prototype._serialize.call(this, {
  43114. name: "SetStateAction",
  43115. properties: [
  43116. BABYLON.Action._GetTargetProperty(this._target),
  43117. { name: "value", value: this.value }
  43118. ]
  43119. }, parent);
  43120. };
  43121. return SetStateAction;
  43122. }(BABYLON.Action));
  43123. BABYLON.SetStateAction = SetStateAction;
  43124. var SetValueAction = (function (_super) {
  43125. __extends(SetValueAction, _super);
  43126. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  43127. var _this = _super.call(this, triggerOptions, condition) || this;
  43128. _this.propertyPath = propertyPath;
  43129. _this.value = value;
  43130. _this._target = _this._effectiveTarget = target;
  43131. return _this;
  43132. }
  43133. SetValueAction.prototype._prepare = function () {
  43134. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  43135. this._property = this._getProperty(this.propertyPath);
  43136. };
  43137. SetValueAction.prototype.execute = function () {
  43138. this._effectiveTarget[this._property] = this.value;
  43139. if (this._target.markAsDirty) {
  43140. this._target.markAsDirty(this._property);
  43141. }
  43142. };
  43143. SetValueAction.prototype.serialize = function (parent) {
  43144. return _super.prototype._serialize.call(this, {
  43145. name: "SetValueAction",
  43146. properties: [
  43147. BABYLON.Action._GetTargetProperty(this._target),
  43148. { name: "propertyPath", value: this.propertyPath },
  43149. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  43150. ]
  43151. }, parent);
  43152. };
  43153. return SetValueAction;
  43154. }(BABYLON.Action));
  43155. BABYLON.SetValueAction = SetValueAction;
  43156. var IncrementValueAction = (function (_super) {
  43157. __extends(IncrementValueAction, _super);
  43158. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  43159. var _this = _super.call(this, triggerOptions, condition) || this;
  43160. _this.propertyPath = propertyPath;
  43161. _this.value = value;
  43162. _this._target = _this._effectiveTarget = target;
  43163. return _this;
  43164. }
  43165. IncrementValueAction.prototype._prepare = function () {
  43166. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  43167. this._property = this._getProperty(this.propertyPath);
  43168. if (typeof this._effectiveTarget[this._property] !== "number") {
  43169. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  43170. }
  43171. };
  43172. IncrementValueAction.prototype.execute = function () {
  43173. this._effectiveTarget[this._property] += this.value;
  43174. if (this._target.markAsDirty) {
  43175. this._target.markAsDirty(this._property);
  43176. }
  43177. };
  43178. IncrementValueAction.prototype.serialize = function (parent) {
  43179. return _super.prototype._serialize.call(this, {
  43180. name: "IncrementValueAction",
  43181. properties: [
  43182. BABYLON.Action._GetTargetProperty(this._target),
  43183. { name: "propertyPath", value: this.propertyPath },
  43184. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  43185. ]
  43186. }, parent);
  43187. };
  43188. return IncrementValueAction;
  43189. }(BABYLON.Action));
  43190. BABYLON.IncrementValueAction = IncrementValueAction;
  43191. var PlayAnimationAction = (function (_super) {
  43192. __extends(PlayAnimationAction, _super);
  43193. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  43194. var _this = _super.call(this, triggerOptions, condition) || this;
  43195. _this.from = from;
  43196. _this.to = to;
  43197. _this.loop = loop;
  43198. _this._target = target;
  43199. return _this;
  43200. }
  43201. PlayAnimationAction.prototype._prepare = function () {
  43202. };
  43203. PlayAnimationAction.prototype.execute = function () {
  43204. var scene = this._actionManager.getScene();
  43205. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  43206. };
  43207. PlayAnimationAction.prototype.serialize = function (parent) {
  43208. return _super.prototype._serialize.call(this, {
  43209. name: "PlayAnimationAction",
  43210. properties: [
  43211. BABYLON.Action._GetTargetProperty(this._target),
  43212. { name: "from", value: String(this.from) },
  43213. { name: "to", value: String(this.to) },
  43214. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  43215. ]
  43216. }, parent);
  43217. };
  43218. return PlayAnimationAction;
  43219. }(BABYLON.Action));
  43220. BABYLON.PlayAnimationAction = PlayAnimationAction;
  43221. var StopAnimationAction = (function (_super) {
  43222. __extends(StopAnimationAction, _super);
  43223. function StopAnimationAction(triggerOptions, target, condition) {
  43224. var _this = _super.call(this, triggerOptions, condition) || this;
  43225. _this._target = target;
  43226. return _this;
  43227. }
  43228. StopAnimationAction.prototype._prepare = function () {
  43229. };
  43230. StopAnimationAction.prototype.execute = function () {
  43231. var scene = this._actionManager.getScene();
  43232. scene.stopAnimation(this._target);
  43233. };
  43234. StopAnimationAction.prototype.serialize = function (parent) {
  43235. return _super.prototype._serialize.call(this, {
  43236. name: "StopAnimationAction",
  43237. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  43238. }, parent);
  43239. };
  43240. return StopAnimationAction;
  43241. }(BABYLON.Action));
  43242. BABYLON.StopAnimationAction = StopAnimationAction;
  43243. var DoNothingAction = (function (_super) {
  43244. __extends(DoNothingAction, _super);
  43245. function DoNothingAction(triggerOptions, condition) {
  43246. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  43247. return _super.call(this, triggerOptions, condition) || this;
  43248. }
  43249. DoNothingAction.prototype.execute = function () {
  43250. };
  43251. DoNothingAction.prototype.serialize = function (parent) {
  43252. return _super.prototype._serialize.call(this, {
  43253. name: "DoNothingAction",
  43254. properties: []
  43255. }, parent);
  43256. };
  43257. return DoNothingAction;
  43258. }(BABYLON.Action));
  43259. BABYLON.DoNothingAction = DoNothingAction;
  43260. var CombineAction = (function (_super) {
  43261. __extends(CombineAction, _super);
  43262. function CombineAction(triggerOptions, children, condition) {
  43263. var _this = _super.call(this, triggerOptions, condition) || this;
  43264. _this.children = children;
  43265. return _this;
  43266. }
  43267. CombineAction.prototype._prepare = function () {
  43268. for (var index = 0; index < this.children.length; index++) {
  43269. this.children[index]._actionManager = this._actionManager;
  43270. this.children[index]._prepare();
  43271. }
  43272. };
  43273. CombineAction.prototype.execute = function (evt) {
  43274. for (var index = 0; index < this.children.length; index++) {
  43275. this.children[index].execute(evt);
  43276. }
  43277. };
  43278. CombineAction.prototype.serialize = function (parent) {
  43279. var serializationObject = _super.prototype._serialize.call(this, {
  43280. name: "CombineAction",
  43281. properties: [],
  43282. combine: []
  43283. }, parent);
  43284. for (var i = 0; i < this.children.length; i++) {
  43285. serializationObject.combine.push(this.children[i].serialize(null));
  43286. }
  43287. return serializationObject;
  43288. };
  43289. return CombineAction;
  43290. }(BABYLON.Action));
  43291. BABYLON.CombineAction = CombineAction;
  43292. var ExecuteCodeAction = (function (_super) {
  43293. __extends(ExecuteCodeAction, _super);
  43294. function ExecuteCodeAction(triggerOptions, func, condition) {
  43295. var _this = _super.call(this, triggerOptions, condition) || this;
  43296. _this.func = func;
  43297. return _this;
  43298. }
  43299. ExecuteCodeAction.prototype.execute = function (evt) {
  43300. this.func(evt);
  43301. };
  43302. return ExecuteCodeAction;
  43303. }(BABYLON.Action));
  43304. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  43305. var SetParentAction = (function (_super) {
  43306. __extends(SetParentAction, _super);
  43307. function SetParentAction(triggerOptions, target, parent, condition) {
  43308. var _this = _super.call(this, triggerOptions, condition) || this;
  43309. _this._target = target;
  43310. _this._parent = parent;
  43311. return _this;
  43312. }
  43313. SetParentAction.prototype._prepare = function () {
  43314. };
  43315. SetParentAction.prototype.execute = function () {
  43316. if (this._target.parent === this._parent) {
  43317. return;
  43318. }
  43319. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  43320. invertParentWorldMatrix.invert();
  43321. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  43322. this._target.parent = this._parent;
  43323. };
  43324. SetParentAction.prototype.serialize = function (parent) {
  43325. return _super.prototype._serialize.call(this, {
  43326. name: "SetParentAction",
  43327. properties: [
  43328. BABYLON.Action._GetTargetProperty(this._target),
  43329. BABYLON.Action._GetTargetProperty(this._parent),
  43330. ]
  43331. }, parent);
  43332. };
  43333. return SetParentAction;
  43334. }(BABYLON.Action));
  43335. BABYLON.SetParentAction = SetParentAction;
  43336. var PlaySoundAction = (function (_super) {
  43337. __extends(PlaySoundAction, _super);
  43338. function PlaySoundAction(triggerOptions, sound, condition) {
  43339. var _this = _super.call(this, triggerOptions, condition) || this;
  43340. _this._sound = sound;
  43341. return _this;
  43342. }
  43343. PlaySoundAction.prototype._prepare = function () {
  43344. };
  43345. PlaySoundAction.prototype.execute = function () {
  43346. if (this._sound !== undefined)
  43347. this._sound.play();
  43348. };
  43349. PlaySoundAction.prototype.serialize = function (parent) {
  43350. return _super.prototype._serialize.call(this, {
  43351. name: "PlaySoundAction",
  43352. properties: [{ name: "sound", value: this._sound.name }]
  43353. }, parent);
  43354. };
  43355. return PlaySoundAction;
  43356. }(BABYLON.Action));
  43357. BABYLON.PlaySoundAction = PlaySoundAction;
  43358. var StopSoundAction = (function (_super) {
  43359. __extends(StopSoundAction, _super);
  43360. function StopSoundAction(triggerOptions, sound, condition) {
  43361. var _this = _super.call(this, triggerOptions, condition) || this;
  43362. _this._sound = sound;
  43363. return _this;
  43364. }
  43365. StopSoundAction.prototype._prepare = function () {
  43366. };
  43367. StopSoundAction.prototype.execute = function () {
  43368. if (this._sound !== undefined)
  43369. this._sound.stop();
  43370. };
  43371. StopSoundAction.prototype.serialize = function (parent) {
  43372. return _super.prototype._serialize.call(this, {
  43373. name: "StopSoundAction",
  43374. properties: [{ name: "sound", value: this._sound.name }]
  43375. }, parent);
  43376. };
  43377. return StopSoundAction;
  43378. }(BABYLON.Action));
  43379. BABYLON.StopSoundAction = StopSoundAction;
  43380. })(BABYLON || (BABYLON = {}));
  43381. //# sourceMappingURL=babylon.directActions.js.map
  43382. var BABYLON;
  43383. (function (BABYLON) {
  43384. var Debug;
  43385. (function (Debug) {
  43386. /**
  43387. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  43388. */
  43389. var SkeletonViewer = (function () {
  43390. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  43391. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  43392. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  43393. this.skeleton = skeleton;
  43394. this.mesh = mesh;
  43395. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  43396. this.renderingGroupId = renderingGroupId;
  43397. this.color = BABYLON.Color3.White();
  43398. this._debugLines = [];
  43399. this._isEnabled = false;
  43400. this._scene = scene;
  43401. this.update();
  43402. this._renderFunction = this.update.bind(this);
  43403. }
  43404. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  43405. get: function () {
  43406. return this._isEnabled;
  43407. },
  43408. set: function (value) {
  43409. if (this._isEnabled === value) {
  43410. return;
  43411. }
  43412. this._isEnabled = value;
  43413. if (value) {
  43414. this._scene.registerBeforeRender(this._renderFunction);
  43415. }
  43416. else {
  43417. this._scene.unregisterBeforeRender(this._renderFunction);
  43418. }
  43419. },
  43420. enumerable: true,
  43421. configurable: true
  43422. });
  43423. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  43424. if (x === void 0) { x = 0; }
  43425. if (y === void 0) { y = 0; }
  43426. if (z === void 0) { z = 0; }
  43427. var tmat = BABYLON.Tmp.Matrix[0];
  43428. var parentBone = bone.getParent();
  43429. tmat.copyFrom(bone.getLocalMatrix());
  43430. if (x !== 0 || y !== 0 || z !== 0) {
  43431. var tmat2 = BABYLON.Tmp.Matrix[1];
  43432. BABYLON.Matrix.IdentityToRef(tmat2);
  43433. tmat2.m[12] = x;
  43434. tmat2.m[13] = y;
  43435. tmat2.m[14] = z;
  43436. tmat2.multiplyToRef(tmat, tmat);
  43437. }
  43438. if (parentBone) {
  43439. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  43440. }
  43441. tmat.multiplyToRef(meshMat, tmat);
  43442. position.x = tmat.m[12];
  43443. position.y = tmat.m[13];
  43444. position.z = tmat.m[14];
  43445. };
  43446. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  43447. var len = bones.length;
  43448. var meshPos = this.mesh.position;
  43449. for (var i = 0; i < len; i++) {
  43450. var bone = bones[i];
  43451. var points = this._debugLines[i];
  43452. if (!points) {
  43453. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  43454. this._debugLines[i] = points;
  43455. }
  43456. this._getBonePosition(points[0], bone, meshMat);
  43457. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  43458. points[0].subtractInPlace(meshPos);
  43459. points[1].subtractInPlace(meshPos);
  43460. }
  43461. };
  43462. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  43463. var len = bones.length;
  43464. var boneNum = 0;
  43465. var meshPos = this.mesh.position;
  43466. for (var i = len - 1; i >= 0; i--) {
  43467. var childBone = bones[i];
  43468. var parentBone = childBone.getParent();
  43469. if (!parentBone) {
  43470. continue;
  43471. }
  43472. var points = this._debugLines[boneNum];
  43473. if (!points) {
  43474. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  43475. this._debugLines[boneNum] = points;
  43476. }
  43477. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  43478. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  43479. points[0].subtractInPlace(meshPos);
  43480. points[1].subtractInPlace(meshPos);
  43481. boneNum++;
  43482. }
  43483. };
  43484. SkeletonViewer.prototype.update = function () {
  43485. if (this.autoUpdateBonesMatrices) {
  43486. this.skeleton.computeAbsoluteTransforms();
  43487. }
  43488. if (this.skeleton.bones[0].length === undefined) {
  43489. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  43490. }
  43491. else {
  43492. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  43493. }
  43494. if (!this._debugMesh) {
  43495. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  43496. this._debugMesh.renderingGroupId = this.renderingGroupId;
  43497. }
  43498. else {
  43499. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  43500. }
  43501. this._debugMesh.position.copyFrom(this.mesh.position);
  43502. this._debugMesh.color = this.color;
  43503. };
  43504. SkeletonViewer.prototype.dispose = function () {
  43505. if (this._debugMesh) {
  43506. this.isEnabled = false;
  43507. this._debugMesh.dispose();
  43508. this._debugMesh = null;
  43509. }
  43510. };
  43511. return SkeletonViewer;
  43512. }());
  43513. Debug.SkeletonViewer = SkeletonViewer;
  43514. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  43515. })(BABYLON || (BABYLON = {}));
  43516. //# sourceMappingURL=babylon.skeletonViewer.js.map
  43517. var BABYLON;
  43518. (function (BABYLON) {
  43519. var Debug;
  43520. (function (Debug) {
  43521. var AxesViewer = (function () {
  43522. function AxesViewer(scene, scaleLines) {
  43523. if (scaleLines === void 0) { scaleLines = 1; }
  43524. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  43525. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  43526. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  43527. this.scaleLines = 1;
  43528. this.scaleLines = scaleLines;
  43529. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  43530. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  43531. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  43532. this._xmesh.renderingGroupId = 2;
  43533. this._ymesh.renderingGroupId = 2;
  43534. this._zmesh.renderingGroupId = 2;
  43535. this._xmesh.material.checkReadyOnlyOnce = true;
  43536. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  43537. this._ymesh.material.checkReadyOnlyOnce = true;
  43538. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  43539. this._zmesh.material.checkReadyOnlyOnce = true;
  43540. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  43541. this.scene = scene;
  43542. }
  43543. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  43544. var scaleLines = this.scaleLines;
  43545. this._xmesh.position.copyFrom(position);
  43546. this._ymesh.position.copyFrom(position);
  43547. this._zmesh.position.copyFrom(position);
  43548. var point2 = this._xline[1];
  43549. point2.x = xaxis.x * scaleLines;
  43550. point2.y = xaxis.y * scaleLines;
  43551. point2.z = xaxis.z * scaleLines;
  43552. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  43553. point2 = this._yline[1];
  43554. point2.x = yaxis.x * scaleLines;
  43555. point2.y = yaxis.y * scaleLines;
  43556. point2.z = yaxis.z * scaleLines;
  43557. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  43558. point2 = this._zline[1];
  43559. point2.x = zaxis.x * scaleLines;
  43560. point2.y = zaxis.y * scaleLines;
  43561. point2.z = zaxis.z * scaleLines;
  43562. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  43563. };
  43564. AxesViewer.prototype.dispose = function () {
  43565. if (this._xmesh) {
  43566. this._xmesh.dispose();
  43567. this._ymesh.dispose();
  43568. this._zmesh.dispose();
  43569. this._xmesh = null;
  43570. this._ymesh = null;
  43571. this._zmesh = null;
  43572. this._xline = null;
  43573. this._yline = null;
  43574. this._zline = null;
  43575. this.scene = null;
  43576. }
  43577. };
  43578. return AxesViewer;
  43579. }());
  43580. Debug.AxesViewer = AxesViewer;
  43581. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  43582. })(BABYLON || (BABYLON = {}));
  43583. //# sourceMappingURL=babylon.axesViewer.js.map
  43584. var BABYLON;
  43585. (function (BABYLON) {
  43586. var Debug;
  43587. (function (Debug) {
  43588. var BoneAxesViewer = (function (_super) {
  43589. __extends(BoneAxesViewer, _super);
  43590. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  43591. if (scaleLines === void 0) { scaleLines = 1; }
  43592. var _this = _super.call(this, scene, scaleLines) || this;
  43593. _this.pos = BABYLON.Vector3.Zero();
  43594. _this.xaxis = BABYLON.Vector3.Zero();
  43595. _this.yaxis = BABYLON.Vector3.Zero();
  43596. _this.zaxis = BABYLON.Vector3.Zero();
  43597. _this.mesh = mesh;
  43598. _this.bone = bone;
  43599. return _this;
  43600. }
  43601. BoneAxesViewer.prototype.update = function () {
  43602. var bone = this.bone;
  43603. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  43604. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  43605. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  43606. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  43607. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  43608. };
  43609. BoneAxesViewer.prototype.dispose = function () {
  43610. if (this.pos) {
  43611. this.pos = null;
  43612. this.xaxis = null;
  43613. this.yaxis = null;
  43614. this.zaxis = null;
  43615. this.mesh = null;
  43616. this.bone = null;
  43617. _super.prototype.dispose.call(this);
  43618. }
  43619. };
  43620. return BoneAxesViewer;
  43621. }(Debug.AxesViewer));
  43622. Debug.BoneAxesViewer = BoneAxesViewer;
  43623. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  43624. })(BABYLON || (BABYLON = {}));
  43625. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  43626. var BABYLON;
  43627. (function (BABYLON) {
  43628. var RayHelper = (function () {
  43629. function RayHelper(ray) {
  43630. this.ray = ray;
  43631. }
  43632. RayHelper.CreateAndShow = function (ray, scene, color) {
  43633. var helper = new RayHelper(ray);
  43634. helper.show(scene, color);
  43635. return helper;
  43636. };
  43637. RayHelper.prototype.show = function (scene, color) {
  43638. if (!this._renderFunction) {
  43639. var ray = this.ray;
  43640. this._renderFunction = this._render.bind(this);
  43641. this._scene = scene;
  43642. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  43643. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  43644. this._scene.registerBeforeRender(this._renderFunction);
  43645. }
  43646. if (color) {
  43647. this._renderLine.color.copyFrom(color);
  43648. }
  43649. };
  43650. RayHelper.prototype.hide = function () {
  43651. if (this._renderFunction) {
  43652. this._scene.unregisterBeforeRender(this._renderFunction);
  43653. this._scene = null;
  43654. this._renderFunction = null;
  43655. this._renderLine.dispose();
  43656. this._renderLine = null;
  43657. this._renderPoints = null;
  43658. }
  43659. };
  43660. RayHelper.prototype._render = function () {
  43661. var ray = this.ray;
  43662. var point = this._renderPoints[1];
  43663. var len = Math.min(ray.length, 1000000);
  43664. point.copyFrom(ray.direction);
  43665. point.scaleInPlace(len);
  43666. point.addInPlace(ray.origin);
  43667. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  43668. };
  43669. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  43670. this._attachedToMesh = mesh;
  43671. var ray = this.ray;
  43672. if (!ray.direction) {
  43673. ray.direction = BABYLON.Vector3.Zero();
  43674. }
  43675. if (!ray.origin) {
  43676. ray.origin = BABYLON.Vector3.Zero();
  43677. }
  43678. if (length) {
  43679. ray.length = length;
  43680. }
  43681. if (!meshSpaceOrigin) {
  43682. meshSpaceOrigin = BABYLON.Vector3.Zero();
  43683. }
  43684. if (!meshSpaceDirection) {
  43685. // -1 so that this will work with Mesh.lookAt
  43686. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  43687. }
  43688. if (!this._meshSpaceDirection) {
  43689. this._meshSpaceDirection = meshSpaceDirection.clone();
  43690. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  43691. }
  43692. else {
  43693. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  43694. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  43695. }
  43696. if (!this._updateToMeshFunction) {
  43697. this._updateToMeshFunction = this._updateToMesh.bind(this);
  43698. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  43699. }
  43700. this._updateToMesh();
  43701. };
  43702. RayHelper.prototype.detachFromMesh = function () {
  43703. if (this._attachedToMesh) {
  43704. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  43705. this._attachedToMesh = null;
  43706. this._updateToMeshFunction = null;
  43707. }
  43708. };
  43709. RayHelper.prototype._updateToMesh = function () {
  43710. var ray = this.ray;
  43711. if (this._attachedToMesh._isDisposed) {
  43712. this.detachFromMesh();
  43713. return;
  43714. }
  43715. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  43716. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  43717. };
  43718. RayHelper.prototype.dispose = function () {
  43719. this.hide();
  43720. this.detachFromMesh();
  43721. this.ray = null;
  43722. };
  43723. return RayHelper;
  43724. }());
  43725. BABYLON.RayHelper = RayHelper;
  43726. })(BABYLON || (BABYLON = {}));
  43727. //# sourceMappingURL=babylon.rayHelper.js.map
  43728. var BABYLON;
  43729. (function (BABYLON) {
  43730. var DebugLayer = (function () {
  43731. function DebugLayer(scene) {
  43732. this._scene = scene;
  43733. }
  43734. /** Creates the inspector window. */
  43735. DebugLayer.prototype._createInspector = function (config) {
  43736. if (config === void 0) { config = {}; }
  43737. var popup = config.popup || false;
  43738. var initialTab = config.initialTab || 0;
  43739. var parentElement = config.parentElement || null;
  43740. if (!this._inspector) {
  43741. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  43742. } // else nothing to do,; instance is already existing
  43743. };
  43744. DebugLayer.prototype.isVisible = function () {
  43745. if (!this._inspector) {
  43746. return false;
  43747. }
  43748. return true;
  43749. };
  43750. DebugLayer.prototype.hide = function () {
  43751. if (this._inspector) {
  43752. try {
  43753. this._inspector.dispose();
  43754. }
  43755. catch (e) {
  43756. // If the inspector has been removed directly from the inspector tool
  43757. }
  43758. this._inspector = null;
  43759. }
  43760. };
  43761. DebugLayer.prototype.show = function (config) {
  43762. if (config === void 0) { config = {}; }
  43763. if (typeof INSPECTOR == 'undefined') {
  43764. // Load inspector and add it to the DOM
  43765. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  43766. }
  43767. else {
  43768. // Otherwise creates the inspector
  43769. this._createInspector(config);
  43770. }
  43771. };
  43772. return DebugLayer;
  43773. }());
  43774. // Get protocol used - http or https
  43775. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  43776. BABYLON.DebugLayer = DebugLayer;
  43777. })(BABYLON || (BABYLON = {}));
  43778. //# sourceMappingURL=babylon.debugLayer.js.map
  43779. var BABYLON;
  43780. (function (BABYLON) {
  43781. var BoundingBoxRenderer = (function () {
  43782. function BoundingBoxRenderer(scene) {
  43783. this.frontColor = new BABYLON.Color3(1, 1, 1);
  43784. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  43785. this.showBackLines = true;
  43786. this.renderList = new BABYLON.SmartArray(32);
  43787. this._vertexBuffers = {};
  43788. this._scene = scene;
  43789. }
  43790. BoundingBoxRenderer.prototype._prepareRessources = function () {
  43791. if (this._colorShader) {
  43792. return;
  43793. }
  43794. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  43795. attributes: [BABYLON.VertexBuffer.PositionKind],
  43796. uniforms: ["world", "viewProjection", "color"]
  43797. });
  43798. var engine = this._scene.getEngine();
  43799. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  43800. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  43801. 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]);
  43802. };
  43803. BoundingBoxRenderer.prototype.reset = function () {
  43804. this.renderList.reset();
  43805. };
  43806. BoundingBoxRenderer.prototype.render = function () {
  43807. if (this.renderList.length === 0) {
  43808. return;
  43809. }
  43810. this._prepareRessources();
  43811. if (!this._colorShader.isReady()) {
  43812. return;
  43813. }
  43814. var engine = this._scene.getEngine();
  43815. engine.setDepthWrite(false);
  43816. this._colorShader._preBind();
  43817. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  43818. var boundingBox = this.renderList.data[boundingBoxIndex];
  43819. var min = boundingBox.minimum;
  43820. var max = boundingBox.maximum;
  43821. var diff = max.subtract(min);
  43822. var median = min.add(diff.scale(0.5));
  43823. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  43824. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  43825. .multiply(boundingBox.getWorldMatrix());
  43826. // VBOs
  43827. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  43828. if (this.showBackLines) {
  43829. // Back
  43830. engine.setDepthFunctionToGreaterOrEqual();
  43831. this._scene.resetCachedMaterial();
  43832. this._colorShader.setColor4("color", this.backColor.toColor4());
  43833. this._colorShader.bind(worldMatrix);
  43834. // Draw order
  43835. engine.draw(false, 0, 24);
  43836. }
  43837. // Front
  43838. engine.setDepthFunctionToLess();
  43839. this._scene.resetCachedMaterial();
  43840. this._colorShader.setColor4("color", this.frontColor.toColor4());
  43841. this._colorShader.bind(worldMatrix);
  43842. // Draw order
  43843. engine.draw(false, 0, 24);
  43844. }
  43845. this._colorShader.unbind();
  43846. engine.setDepthFunctionToLessOrEqual();
  43847. engine.setDepthWrite(true);
  43848. };
  43849. BoundingBoxRenderer.prototype.dispose = function () {
  43850. if (!this._colorShader) {
  43851. return;
  43852. }
  43853. this.renderList.dispose();
  43854. this._colorShader.dispose();
  43855. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  43856. if (buffer) {
  43857. buffer.dispose();
  43858. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  43859. }
  43860. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  43861. };
  43862. return BoundingBoxRenderer;
  43863. }());
  43864. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  43865. })(BABYLON || (BABYLON = {}));
  43866. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  43867. 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#include<fresnelFunction>\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#endif\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#ifdef CAMERACOLORGRADING\n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurves>\n#endif\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<helperFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) \nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#ifdef ALPHAFROMALBEDO\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#if defined(ALPHATEST) && defined(ALPHATESTVALUE)\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef METALLICMAP\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nfloat NdotL=-1.;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\n\n\nfloat reflectance90=clamp(reflectance*25.0,0.0,1.0);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nlightingInfo info;\nfloat shadow=1.; \n#include<lightFragment>[0..maxSimultaneousLights]\nvec3 lightDiffuseContribution=diffuseBase;\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=specularBase*vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif ((vMicrosurfaceTextureLods.y-lodRefraction)>4.0)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif ((vMicrosurfaceTextureLods.y-lodReflection)>4.0)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0,0.0,0.0);\n#ifdef REFRACTION\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nsurfaceRefractionColor*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=surfaceRefractionColor*transmission;\n#endif\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\nvec3 finalDiffuse=lightDiffuseContribution;\n#ifndef EMISSIVEASILLUMINATION\nfinalDiffuse+=surfaceEmissiveColor;\n#endif\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\nfinalDiffuse=(finalDiffuse*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance)*ambientOcclusionColor;\nfloat luminanceOverAlpha=0.0;\n#ifdef RADIANCEOVERALPHA\nluminanceOverAlpha+=getLuminance(environmentRadiance);\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#ifdef SPECULAROVERALPHA\nluminanceOverAlpha+=getLuminance(finalSpecular);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nfinalSpecular*=vLightingIntensity.x;\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*alpha,0.,1.);\n#endif\n\n\nvec4 finalColor=vec4(finalDiffuse+finalSpecular+environmentRadiance+refractance,alpha);\n#ifdef EMISSIVEASILLUMINATION\nfinalColor.rgb+=(surfaceEmissiveColor*vLightingIntensity.y);\n#endif\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\n#ifdef LDROUTPUT\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\n#endif\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","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]\nvoid main(void)\n{\nvec4 blend=vec4(0.);\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\ngl_FragColor=blend;\n}","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst float GammaEncodePowerApprox=1.0/2.2;\nconst float LinearEncodePowerApprox=2.2;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nuniform float contrast;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\nuniform float cameraExposureLinear;\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform sampler2D txColorTransform;\nuniform vec4 colorTransformSettings;\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color)\n{\nfloat sliceSize=2.0*colorTransformSettings.y; \nfloat sliceContinuous=(color.y-colorTransformSettings.y)*colorTransformSettings.z;\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\nvec2 sliceUV=color.xz;\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=result.bgr;\nreturn color;\n}\nvec4 applyImageProcessing(vec4 result,vec2 viewportXY){\n#ifndef FROMLINEARSPACE\n\nresult.rgb=pow(result.rgb,vec3(LinearEncodePowerApprox));\n#endif\nresult.rgb*=cameraExposureLinear;\n#ifdef VIGNETTE\n\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING \nfloat tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=pow(result.rgb,vec3(GammaEncodePowerApprox));\nresult.rgb=clamp(result.rgb,0.0,1.0);\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput).rgb;\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=dot(result.rgb,RGBLuminanceCoefficients);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}\nvoid main(void) \n{\nvec4 result=texture2D(textureSampler,vUV);\nvec2 viewportXY=vUV*2.0-1.0;\nresult=applyImageProcessing(result,viewportXY);\ngl_FragColor=result;\n}","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#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition> \n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#include<colorCurves>\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n#ifdef CAMERACOLORGRADING\ncolor=colorGrades(color);\n#endif\n#ifdef CAMERACOLORCURVES\ncolor.rgb=applyColorCurves(color.rgb);\n#endif\ngl_FragColor=color;\n}"};
  43868. 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#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\n#else\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec2 vMicrosurfaceTextureLods;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform vec4 opacityParts;\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","colorGradingDefinition":"uniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;","colorCurvesDefinition":"uniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform vec4 vCameraColorCurveNegative;","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-darkness,0.,1.); \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,0.,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-darkness,0.,1.);\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,0.,1.);\n\n\n\n\n\nreturn esm;\n}\n#endif","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kPi=3.1415926535897932384626433832795;\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat Square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,vec3(0.2126,0.7152,0.0722)),0.,1.);\n}\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=Square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat getMipMapIndexFromAverageSlope(float maxMipLevel,float alpha)\n{\n\n\n\n\n\n\n\nfloat mip=kRougnhessToAlphaOffset+maxMipLevel+(maxMipLevel*kRougnhessToAlphaScale*log2(alpha));\nreturn clamp(mip,0.,maxMipLevel);\n}\nfloat getMipMapIndexFromAverageSlopeWithPMREM(float maxMipLevel,float alphaG)\n{\nfloat specularPower=clamp(2./alphaG-2.,0.000001,2048.);\n\nreturn clamp(- 0.5*log2(specularPower)+5.5,0.,maxMipLevel);\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=Square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(kPi*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 FresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 specularColor,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nvec3 fresnel=fresnelSchlickGGX(VdotH,specularColor,reflectance90);\nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nreturn fresnel*specTerm*kPi; \n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat diffuseFresnelTerm =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn diffuseFresnelTerm*NdotL;\n\n\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nfloat kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn vec3(pow(color.r,2.2),pow(color.g,2.2),pow(color.b,2.2));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn vec3(pow(color.r,1.0/2.2),pow(color.g,1.0/2.2),pow(color.b,1.0/2.2));\n}\n#ifdef CAMERATONEMAP\nvec3 toneMaps(vec3 color)\n{\ncolor=max(color,0.0);\n\ncolor.rgb=color.rgb*vCameraInfos.x;\nfloat tuning=1.5; \n\n\nvec3 tonemapped=1.0-exp2(-color.rgb*tuning); \ncolor.rgb=mix(color.rgb,tonemapped,1.0);\nreturn color;\n}\n#endif\n#ifdef CAMERACONTRAST\nvec4 contrasts(vec4 color)\n{\ncolor=clamp(color,0.0,1.0);\nvec3 resultHighContrast=color.rgb*color.rgb*(3.0-2.0*color.rgb);\nfloat contrast=vCameraInfos.y;\nif (contrast<1.0)\n{\n\ncolor.rgb=mix(vec3(0.5,0.5,0.5),color.rgb,contrast);\n}\nelse\n{\n\ncolor.rgb=mix(color.rgb,resultHighContrast,contrast-1.0);\n}\nreturn color;\n}\n#endif","colorGrading":"vec4 colorGrades(vec4 color) \n{ \n\nfloat sliceContinuous=color.z*vCameraColorGradingInfos.z;\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger; \n\nvec2 sliceUV=color.xy*vCameraColorGradingScaleOffset.xy+vCameraColorGradingScaleOffset.zw;\n\n\nsliceUV.x+=sliceInteger*vCameraColorGradingInfos.w;\nvec4 slice0Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nsliceUV.x+=vCameraColorGradingInfos.w;\nvec4 slice1Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=mix(color.rgb,result,vCameraColorGradingInfos.x);\nreturn color;\n}","colorCurves":"const vec3 HDTVRec709_RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvec3 applyColorCurves(vec3 original) {\nvec3 result=original;\n\n\n\nfloat luma=dot(result.rgb,HDTVRec709_RGBLuminanceCoefficients);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0,0.0),vec2(1.0,1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma,luma,luma),result.rgb,colorCurve.a);\nreturn result;\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX;\nuniform vec3 vSphericalYY;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 EnvironmentIrradiance(vec3 normal)\n{\n\n\n\nvec3 result =\nvSphericalX*normal.x +\nvSphericalY*normal.y +\nvSphericalZ*normal.z +\nvSphericalXX*normal.x*normal.x +\nvSphericalYY*normal.y*normal.y +\nvSphericalZZ*normal.z*normal.z +\nvSphericalYZ*normal.y*normal.z +\nvSphericalZX*normal.z*normal.x +\nvSphericalXY*normal.x*normal.y;\nreturn result.rgb;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.0001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat cosHalfAngle=cos(lightAngle*0.5);\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=lightAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=max(0.00000000001,dot(vNormal,lightDirection));\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=max(0.00000000001,dot(vNormal,directionToLightCenterW));\nfloat VdotH=clamp(dot(viewDirectionW,H),0.00000000001,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nNdotL=max(0.00000000001,NdotL);\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm;\n#endif\nreturn result;\n}","helperFunctions":"mat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n#ifdef USERIGHTHANDEDSYSTEM\nbinormal=-binormal;\n#endif\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\n#ifdef INVERTNORMALMAPX\nmap.x=1.0-map.x;\n#endif\n#ifdef INVERTNORMALMAPY\nmap.y=1.0-map.y;\n#endif\nmap=map*255./127.-128./127.;\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nnormalW=normalize(normalW*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef 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":"blend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n","kernelBlurFragment2":"blend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\n","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","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};"};
  43869. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  43870. module.exports = BABYLON;
  43871. };