babylon.max.js 2.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. var BABYLON;
  18. (function (BABYLON) {
  19. BABYLON.ToGammaSpace = 1 / 2.2;
  20. BABYLON.ToLinearSpace = 2.2;
  21. BABYLON.Epsilon = 0.001;
  22. var MathTools = (function () {
  23. function MathTools() {
  24. }
  25. /**
  26. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  27. */
  28. MathTools.WithinEpsilon = function (a, b, epsilon) {
  29. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  30. var num = a - b;
  31. return -epsilon <= num && num <= epsilon;
  32. };
  33. /**
  34. * Returns a string : the upper case translation of the number i to hexadecimal.
  35. */
  36. MathTools.ToHex = function (i) {
  37. var str = i.toString(16);
  38. if (i <= 15) {
  39. return ("0" + str).toUpperCase();
  40. }
  41. return str.toUpperCase();
  42. };
  43. /**
  44. * Returns -1 if value is negative and +1 is value is positive.
  45. * Returns the value itself if it's equal to zero.
  46. */
  47. MathTools.Sign = function (value) {
  48. value = +value; // convert to a number
  49. if (value === 0 || isNaN(value))
  50. return value;
  51. return value > 0 ? 1 : -1;
  52. };
  53. /**
  54. * Returns the value itself if it's between min and max.
  55. * Returns min if the value is lower than min.
  56. * Returns max if the value is greater than max.
  57. */
  58. MathTools.Clamp = function (value, min, max) {
  59. if (min === void 0) { min = 0; }
  60. if (max === void 0) { max = 1; }
  61. return Math.min(max, Math.max(min, value));
  62. };
  63. return MathTools;
  64. }());
  65. BABYLON.MathTools = MathTools;
  66. var Scalar = (function () {
  67. function Scalar() {
  68. }
  69. /**
  70. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  71. */
  72. Scalar.Lerp = function (start, end, amount) {
  73. return start + ((end - start) * amount);
  74. };
  75. /**
  76. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  77. */
  78. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  79. var squared = amount * amount;
  80. var cubed = amount * squared;
  81. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  82. var part2 = (-2.0 * cubed) + (3.0 * squared);
  83. var part3 = (cubed - (2.0 * squared)) + amount;
  84. var part4 = cubed - squared;
  85. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  86. };
  87. return Scalar;
  88. }());
  89. BABYLON.Scalar = Scalar;
  90. var Color3 = (function () {
  91. /**
  92. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  93. */
  94. function Color3(r, g, b) {
  95. if (r === void 0) { r = 0; }
  96. if (g === void 0) { g = 0; }
  97. if (b === void 0) { b = 0; }
  98. this.r = r;
  99. this.g = g;
  100. this.b = b;
  101. }
  102. /**
  103. * Returns a string with the Color3 current values.
  104. */
  105. Color3.prototype.toString = function () {
  106. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  107. };
  108. /**
  109. * Returns the string "Color3".
  110. */
  111. Color3.prototype.getClassName = function () {
  112. return "Color3";
  113. };
  114. /**
  115. * Returns the Color3 hash code.
  116. */
  117. Color3.prototype.getHashCode = function () {
  118. var hash = this.r || 0;
  119. hash = (hash * 397) ^ (this.g || 0);
  120. hash = (hash * 397) ^ (this.b || 0);
  121. return hash;
  122. };
  123. // Operators
  124. /**
  125. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  126. * Returns the Color3.
  127. */
  128. Color3.prototype.toArray = function (array, index) {
  129. if (index === undefined) {
  130. index = 0;
  131. }
  132. array[index] = this.r;
  133. array[index + 1] = this.g;
  134. array[index + 2] = this.b;
  135. return this;
  136. };
  137. /**
  138. * Returns a new Color4 object from the current Color3 and the passed alpha.
  139. */
  140. Color3.prototype.toColor4 = function (alpha) {
  141. if (alpha === void 0) { alpha = 1; }
  142. return new Color4(this.r, this.g, this.b, alpha);
  143. };
  144. /**
  145. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  146. */
  147. Color3.prototype.asArray = function () {
  148. var result = [];
  149. this.toArray(result, 0);
  150. return result;
  151. };
  152. /**
  153. * Returns the luminance value (float).
  154. */
  155. Color3.prototype.toLuminance = function () {
  156. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  157. };
  158. /**
  159. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  160. * Returns this new object.
  161. */
  162. Color3.prototype.multiply = function (otherColor) {
  163. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  164. };
  165. /**
  166. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  167. * Returns the current Color3.
  168. */
  169. Color3.prototype.multiplyToRef = function (otherColor, result) {
  170. result.r = this.r * otherColor.r;
  171. result.g = this.g * otherColor.g;
  172. result.b = this.b * otherColor.b;
  173. return this;
  174. };
  175. /**
  176. * Boolean : True if the rgb values are equal to the passed ones.
  177. */
  178. Color3.prototype.equals = function (otherColor) {
  179. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  180. };
  181. /**
  182. * Boolean : True if the rgb values are equal to the passed ones.
  183. */
  184. Color3.prototype.equalsFloats = function (r, g, b) {
  185. return this.r === r && this.g === g && this.b === b;
  186. };
  187. /**
  188. * Multiplies in place each rgb value by scale.
  189. * Returns the updated Color3.
  190. */
  191. Color3.prototype.scale = function (scale) {
  192. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  193. };
  194. /**
  195. * Multiplies the rgb values by scale and stores the result into "result".
  196. * Returns the unmodified current Color3.
  197. */
  198. Color3.prototype.scaleToRef = function (scale, result) {
  199. result.r = this.r * scale;
  200. result.g = this.g * scale;
  201. result.b = this.b * scale;
  202. return this;
  203. };
  204. /**
  205. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  206. */
  207. Color3.prototype.add = function (otherColor) {
  208. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  209. };
  210. /**
  211. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  212. * Returns the unmodified current Color3.
  213. */
  214. Color3.prototype.addToRef = function (otherColor, result) {
  215. result.r = this.r + otherColor.r;
  216. result.g = this.g + otherColor.g;
  217. result.b = this.b + otherColor.b;
  218. return this;
  219. };
  220. /**
  221. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  222. */
  223. Color3.prototype.subtract = function (otherColor) {
  224. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  225. };
  226. /**
  227. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  228. * Returns the unmodified current Color3.
  229. */
  230. Color3.prototype.subtractToRef = function (otherColor, result) {
  231. result.r = this.r - otherColor.r;
  232. result.g = this.g - otherColor.g;
  233. result.b = this.b - otherColor.b;
  234. return this;
  235. };
  236. /**
  237. * Returns a new Color3 copied the current one.
  238. */
  239. Color3.prototype.clone = function () {
  240. return new Color3(this.r, this.g, this.b);
  241. };
  242. /**
  243. * Copies the rgb values from the source in the current Color3.
  244. * Returns the updated Color3.
  245. */
  246. Color3.prototype.copyFrom = function (source) {
  247. this.r = source.r;
  248. this.g = source.g;
  249. this.b = source.b;
  250. return this;
  251. };
  252. /**
  253. * Updates the Color3 rgb values from the passed floats.
  254. * Returns the Color3.
  255. */
  256. Color3.prototype.copyFromFloats = function (r, g, b) {
  257. this.r = r;
  258. this.g = g;
  259. this.b = b;
  260. return this;
  261. };
  262. /**
  263. * Updates the Color3 rgb values from the passed floats.
  264. * Returns the Color3.
  265. */
  266. Color3.prototype.set = function (r, g, b) {
  267. return this.copyFromFloats(r, g, b);
  268. };
  269. /**
  270. * Returns the Color3 hexadecimal code as a string.
  271. */
  272. Color3.prototype.toHexString = function () {
  273. var intR = (this.r * 255) | 0;
  274. var intG = (this.g * 255) | 0;
  275. var intB = (this.b * 255) | 0;
  276. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  277. };
  278. /**
  279. * Returns a new Color3 converted to linear space.
  280. */
  281. Color3.prototype.toLinearSpace = function () {
  282. var convertedColor = new Color3();
  283. this.toLinearSpaceToRef(convertedColor);
  284. return convertedColor;
  285. };
  286. /**
  287. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  288. * Returns the unmodified Color3.
  289. */
  290. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  291. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  292. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  293. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  294. return this;
  295. };
  296. /**
  297. * Returns a new Color3 converted to gamma space.
  298. */
  299. Color3.prototype.toGammaSpace = function () {
  300. var convertedColor = new Color3();
  301. this.toGammaSpaceToRef(convertedColor);
  302. return convertedColor;
  303. };
  304. /**
  305. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  306. * Returns the unmodified Color3.
  307. */
  308. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  309. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  310. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  311. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  312. return this;
  313. };
  314. // Statics
  315. /**
  316. * Creates a new Color3 from the string containing valid hexadecimal values.
  317. */
  318. Color3.FromHexString = function (hex) {
  319. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  320. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  321. return new Color3(0, 0, 0);
  322. }
  323. var r = parseInt(hex.substring(1, 3), 16);
  324. var g = parseInt(hex.substring(3, 5), 16);
  325. var b = parseInt(hex.substring(5, 7), 16);
  326. return Color3.FromInts(r, g, b);
  327. };
  328. /**
  329. * Creates a new Vector3 from the startind index of the passed array.
  330. */
  331. Color3.FromArray = function (array, offset) {
  332. if (offset === void 0) { offset = 0; }
  333. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  334. };
  335. /**
  336. * Creates a new Color3 from integer values ( < 256).
  337. */
  338. Color3.FromInts = function (r, g, b) {
  339. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  340. };
  341. /**
  342. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  343. */
  344. Color3.Lerp = function (start, end, amount) {
  345. var r = start.r + ((end.r - start.r) * amount);
  346. var g = start.g + ((end.g - start.g) * amount);
  347. var b = start.b + ((end.b - start.b) * amount);
  348. return new Color3(r, g, b);
  349. };
  350. Color3.Red = function () { return new Color3(1, 0, 0); };
  351. Color3.Green = function () { return new Color3(0, 1, 0); };
  352. Color3.Blue = function () { return new Color3(0, 0, 1); };
  353. Color3.Black = function () { return new Color3(0, 0, 0); };
  354. Color3.White = function () { return new Color3(1, 1, 1); };
  355. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  356. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  357. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  358. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  359. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  360. return Color3;
  361. }());
  362. BABYLON.Color3 = Color3;
  363. var Color4 = (function () {
  364. /**
  365. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  366. */
  367. function Color4(r, g, b, a) {
  368. this.r = r;
  369. this.g = g;
  370. this.b = b;
  371. this.a = a;
  372. }
  373. // Operators
  374. /**
  375. * Adds in place the passed Color4 values to the current Color4.
  376. * Returns the updated Color4.
  377. */
  378. Color4.prototype.addInPlace = function (right) {
  379. this.r += right.r;
  380. this.g += right.g;
  381. this.b += right.b;
  382. this.a += right.a;
  383. return this;
  384. };
  385. /**
  386. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  387. */
  388. Color4.prototype.asArray = function () {
  389. var result = [];
  390. this.toArray(result, 0);
  391. return result;
  392. };
  393. /**
  394. * Stores from the starting index in the passed array the Color4 successive values.
  395. * Returns the Color4.
  396. */
  397. Color4.prototype.toArray = function (array, index) {
  398. if (index === undefined) {
  399. index = 0;
  400. }
  401. array[index] = this.r;
  402. array[index + 1] = this.g;
  403. array[index + 2] = this.b;
  404. array[index + 3] = this.a;
  405. return this;
  406. };
  407. /**
  408. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  409. */
  410. Color4.prototype.add = function (right) {
  411. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  412. };
  413. /**
  414. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  415. */
  416. Color4.prototype.subtract = function (right) {
  417. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  418. };
  419. /**
  420. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  421. * Returns the Color4.
  422. */
  423. Color4.prototype.subtractToRef = function (right, result) {
  424. result.r = this.r - right.r;
  425. result.g = this.g - right.g;
  426. result.b = this.b - right.b;
  427. result.a = this.a - right.a;
  428. return this;
  429. };
  430. /**
  431. * Creates a new Color4 with the current Color4 values multiplied by scale.
  432. */
  433. Color4.prototype.scale = function (scale) {
  434. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  435. };
  436. /**
  437. * Multiplies the current Color4 values by scale and stores the result in "result".
  438. * Returns the Color4.
  439. */
  440. Color4.prototype.scaleToRef = function (scale, result) {
  441. result.r = this.r * scale;
  442. result.g = this.g * scale;
  443. result.b = this.b * scale;
  444. result.a = this.a * scale;
  445. return this;
  446. };
  447. /**
  448. * Multipy an RGBA Color4 value by another and return a new Color4 object
  449. * @param color The Color4 (RGBA) value to multiply by
  450. * @returns A new Color4.
  451. */
  452. Color4.prototype.multiply = function (color) {
  453. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  454. };
  455. /**
  456. * Multipy an RGBA Color4 value by another and push the result in a reference value
  457. * @param color The Color4 (RGBA) value to multiply by
  458. * @param result The Color4 (RGBA) to fill the result in
  459. * @returns the result Color4.
  460. */
  461. Color4.prototype.multiplyToRef = function (color, result) {
  462. result.r = this.r * color.r;
  463. result.g = this.g * color.g;
  464. result.b = this.b * color.b;
  465. result.a = this.a * color.a;
  466. return result;
  467. };
  468. /**
  469. * Returns a string with the Color4 values.
  470. */
  471. Color4.prototype.toString = function () {
  472. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  473. };
  474. /**
  475. * Returns the string "Color4"
  476. */
  477. Color4.prototype.getClassName = function () {
  478. return "Color4";
  479. };
  480. /**
  481. * Return the Color4 hash code as a number.
  482. */
  483. Color4.prototype.getHashCode = function () {
  484. var hash = this.r || 0;
  485. hash = (hash * 397) ^ (this.g || 0);
  486. hash = (hash * 397) ^ (this.b || 0);
  487. hash = (hash * 397) ^ (this.a || 0);
  488. return hash;
  489. };
  490. /**
  491. * Creates a new Color4 copied from the current one.
  492. */
  493. Color4.prototype.clone = function () {
  494. return new Color4(this.r, this.g, this.b, this.a);
  495. };
  496. /**
  497. * Copies the passed Color4 values into the current one.
  498. * Returns the updated Color4.
  499. */
  500. Color4.prototype.copyFrom = function (source) {
  501. this.r = source.r;
  502. this.g = source.g;
  503. this.b = source.b;
  504. this.a = source.a;
  505. return this;
  506. };
  507. /**
  508. * Copies the passed float values into the current one.
  509. * Returns the updated Color4.
  510. */
  511. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  512. this.r = r;
  513. this.g = g;
  514. this.b = b;
  515. this.a = a;
  516. return this;
  517. };
  518. /**
  519. * Copies the passed float values into the current one.
  520. * Returns the updated Color4.
  521. */
  522. Color4.prototype.set = function (r, g, b, a) {
  523. return this.copyFromFloats(r, g, b, a);
  524. };
  525. /**
  526. * Returns a string containing the hexadecimal Color4 code.
  527. */
  528. Color4.prototype.toHexString = function () {
  529. var intR = (this.r * 255) | 0;
  530. var intG = (this.g * 255) | 0;
  531. var intB = (this.b * 255) | 0;
  532. var intA = (this.a * 255) | 0;
  533. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  534. };
  535. // Statics
  536. /**
  537. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  538. */
  539. Color4.FromHexString = function (hex) {
  540. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  541. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  542. return new Color4(0.0, 0.0, 0.0, 0.0);
  543. }
  544. var r = parseInt(hex.substring(1, 3), 16);
  545. var g = parseInt(hex.substring(3, 5), 16);
  546. var b = parseInt(hex.substring(5, 7), 16);
  547. var a = parseInt(hex.substring(7, 9), 16);
  548. return Color4.FromInts(r, g, b, a);
  549. };
  550. /**
  551. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  552. */
  553. Color4.Lerp = function (left, right, amount) {
  554. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  555. Color4.LerpToRef(left, right, amount, result);
  556. return result;
  557. };
  558. /**
  559. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  560. */
  561. Color4.LerpToRef = function (left, right, amount, result) {
  562. result.r = left.r + (right.r - left.r) * amount;
  563. result.g = left.g + (right.g - left.g) * amount;
  564. result.b = left.b + (right.b - left.b) * amount;
  565. result.a = left.a + (right.a - left.a) * amount;
  566. };
  567. /**
  568. * Creates a new Color4 from the starting index element of the passed array.
  569. */
  570. Color4.FromArray = function (array, offset) {
  571. if (offset === void 0) { offset = 0; }
  572. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  573. };
  574. /**
  575. * Creates a new Color4 from the passed integers ( < 256 ).
  576. */
  577. Color4.FromInts = function (r, g, b, a) {
  578. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  579. };
  580. Color4.CheckColors4 = function (colors, count) {
  581. // Check if color3 was used
  582. if (colors.length === count * 3) {
  583. var colors4 = [];
  584. for (var index = 0; index < colors.length; index += 3) {
  585. var newIndex = (index / 3) * 4;
  586. colors4[newIndex] = colors[index];
  587. colors4[newIndex + 1] = colors[index + 1];
  588. colors4[newIndex + 2] = colors[index + 2];
  589. colors4[newIndex + 3] = 1.0;
  590. }
  591. return colors4;
  592. }
  593. return colors;
  594. };
  595. return Color4;
  596. }());
  597. BABYLON.Color4 = Color4;
  598. var Vector2 = (function () {
  599. /**
  600. * Creates a new Vector2 from the passed x and y coordinates.
  601. */
  602. function Vector2(x, y) {
  603. this.x = x;
  604. this.y = y;
  605. }
  606. /**
  607. * Returns a string with the Vector2 coordinates.
  608. */
  609. Vector2.prototype.toString = function () {
  610. return "{X: " + this.x + " Y:" + this.y + "}";
  611. };
  612. /**
  613. * Returns the string "Vector2"
  614. */
  615. Vector2.prototype.getClassName = function () {
  616. return "Vector2";
  617. };
  618. /**
  619. * Returns the Vector2 hash code as a number.
  620. */
  621. Vector2.prototype.getHashCode = function () {
  622. var hash = this.x || 0;
  623. hash = (hash * 397) ^ (this.y || 0);
  624. return hash;
  625. };
  626. // Operators
  627. /**
  628. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  629. * Returns the Vector2.
  630. */
  631. Vector2.prototype.toArray = function (array, index) {
  632. if (index === void 0) { index = 0; }
  633. array[index] = this.x;
  634. array[index + 1] = this.y;
  635. return this;
  636. };
  637. /**
  638. * Returns a new array with 2 elements : the Vector2 coordinates.
  639. */
  640. Vector2.prototype.asArray = function () {
  641. var result = [];
  642. this.toArray(result, 0);
  643. return result;
  644. };
  645. /**
  646. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  647. * Returns the updated Vector2.
  648. */
  649. Vector2.prototype.copyFrom = function (source) {
  650. this.x = source.x;
  651. this.y = source.y;
  652. return this;
  653. };
  654. /**
  655. * Sets the Vector2 coordinates with the passed floats.
  656. * Returns the updated Vector2.
  657. */
  658. Vector2.prototype.copyFromFloats = function (x, y) {
  659. this.x = x;
  660. this.y = y;
  661. return this;
  662. };
  663. /**
  664. * Sets the Vector2 coordinates with the passed floats.
  665. * Returns the updated Vector2.
  666. */
  667. Vector2.prototype.set = function (x, y) {
  668. return this.copyFromFloats(x, y);
  669. };
  670. /**
  671. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  672. */
  673. Vector2.prototype.add = function (otherVector) {
  674. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  675. };
  676. /**
  677. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  678. * Returns the Vector2.
  679. */
  680. Vector2.prototype.addToRef = function (otherVector, result) {
  681. result.x = this.x + otherVector.x;
  682. result.y = this.y + otherVector.y;
  683. return this;
  684. };
  685. /**
  686. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  687. * Returns the updated Vector2.
  688. */
  689. Vector2.prototype.addInPlace = function (otherVector) {
  690. this.x += otherVector.x;
  691. this.y += otherVector.y;
  692. return this;
  693. };
  694. /**
  695. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  696. */
  697. Vector2.prototype.addVector3 = function (otherVector) {
  698. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  699. };
  700. /**
  701. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  702. */
  703. Vector2.prototype.subtract = function (otherVector) {
  704. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  705. };
  706. /**
  707. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  708. * Returns the Vector2.
  709. */
  710. Vector2.prototype.subtractToRef = function (otherVector, result) {
  711. result.x = this.x - otherVector.x;
  712. result.y = this.y - otherVector.y;
  713. return this;
  714. };
  715. /**
  716. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  717. * Returns the updated Vector2.
  718. */
  719. Vector2.prototype.subtractInPlace = function (otherVector) {
  720. this.x -= otherVector.x;
  721. this.y -= otherVector.y;
  722. return this;
  723. };
  724. /**
  725. * Multiplies in place the current Vector2 coordinates by the passed ones.
  726. * Returns the updated Vector2.
  727. */
  728. Vector2.prototype.multiplyInPlace = function (otherVector) {
  729. this.x *= otherVector.x;
  730. this.y *= otherVector.y;
  731. return this;
  732. };
  733. /**
  734. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  735. */
  736. Vector2.prototype.multiply = function (otherVector) {
  737. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  738. };
  739. /**
  740. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  741. * Returns the Vector2.
  742. */
  743. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  744. result.x = this.x * otherVector.x;
  745. result.y = this.y * otherVector.y;
  746. return this;
  747. };
  748. /**
  749. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  750. */
  751. Vector2.prototype.multiplyByFloats = function (x, y) {
  752. return new Vector2(this.x * x, this.y * y);
  753. };
  754. /**
  755. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  756. */
  757. Vector2.prototype.divide = function (otherVector) {
  758. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  759. };
  760. /**
  761. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  762. * Returns the Vector2.
  763. */
  764. Vector2.prototype.divideToRef = function (otherVector, result) {
  765. result.x = this.x / otherVector.x;
  766. result.y = this.y / otherVector.y;
  767. return this;
  768. };
  769. /**
  770. * Returns a new Vector2 with current Vector2 negated coordinates.
  771. */
  772. Vector2.prototype.negate = function () {
  773. return new Vector2(-this.x, -this.y);
  774. };
  775. /**
  776. * Multiply the Vector2 coordinates by scale.
  777. * Returns the updated Vector2.
  778. */
  779. Vector2.prototype.scaleInPlace = function (scale) {
  780. this.x *= scale;
  781. this.y *= scale;
  782. return this;
  783. };
  784. /**
  785. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  786. */
  787. Vector2.prototype.scale = function (scale) {
  788. return new Vector2(this.x * scale, this.y * scale);
  789. };
  790. /**
  791. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  792. */
  793. Vector2.prototype.equals = function (otherVector) {
  794. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  795. };
  796. /**
  797. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  798. */
  799. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  800. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  801. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  802. };
  803. // Properties
  804. /**
  805. * Returns the vector length (float).
  806. */
  807. Vector2.prototype.length = function () {
  808. return Math.sqrt(this.x * this.x + this.y * this.y);
  809. };
  810. /**
  811. * Returns the vector squared length (float);
  812. */
  813. Vector2.prototype.lengthSquared = function () {
  814. return (this.x * this.x + this.y * this.y);
  815. };
  816. // Methods
  817. /**
  818. * Normalize the vector.
  819. * Returns the updated Vector2.
  820. */
  821. Vector2.prototype.normalize = function () {
  822. var len = this.length();
  823. if (len === 0)
  824. return this;
  825. var num = 1.0 / len;
  826. this.x *= num;
  827. this.y *= num;
  828. return this;
  829. };
  830. /**
  831. * Returns a new Vector2 copied from the Vector2.
  832. */
  833. Vector2.prototype.clone = function () {
  834. return new Vector2(this.x, this.y);
  835. };
  836. // Statics
  837. /**
  838. * Returns a new Vector2(0, 0)
  839. */
  840. Vector2.Zero = function () {
  841. return new Vector2(0, 0);
  842. };
  843. /**
  844. * Returns a new Vector2 set from the passed index element of the passed array.
  845. */
  846. Vector2.FromArray = function (array, offset) {
  847. if (offset === void 0) { offset = 0; }
  848. return new Vector2(array[offset], array[offset + 1]);
  849. };
  850. /**
  851. * Sets "result" from the passed index element of the passed array.
  852. */
  853. Vector2.FromArrayToRef = function (array, offset, result) {
  854. result.x = array[offset];
  855. result.y = array[offset + 1];
  856. };
  857. /**
  858. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  859. */
  860. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  861. var squared = amount * amount;
  862. var cubed = amount * squared;
  863. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  864. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  865. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  866. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  867. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  868. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  869. return new Vector2(x, y);
  870. };
  871. /**
  872. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  873. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  874. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  875. */
  876. Vector2.Clamp = function (value, min, max) {
  877. var x = value.x;
  878. x = (x > max.x) ? max.x : x;
  879. x = (x < min.x) ? min.x : x;
  880. var y = value.y;
  881. y = (y > max.y) ? max.y : y;
  882. y = (y < min.y) ? min.y : y;
  883. return new Vector2(x, y);
  884. };
  885. /**
  886. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  887. */
  888. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  889. var squared = amount * amount;
  890. var cubed = amount * squared;
  891. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  892. var part2 = (-2.0 * cubed) + (3.0 * squared);
  893. var part3 = (cubed - (2.0 * squared)) + amount;
  894. var part4 = cubed - squared;
  895. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  896. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  897. return new Vector2(x, y);
  898. };
  899. /**
  900. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  901. */
  902. Vector2.Lerp = function (start, end, amount) {
  903. var x = start.x + ((end.x - start.x) * amount);
  904. var y = start.y + ((end.y - start.y) * amount);
  905. return new Vector2(x, y);
  906. };
  907. /**
  908. * Returns the dot product (float) of the vector "left" and the vector "right".
  909. */
  910. Vector2.Dot = function (left, right) {
  911. return left.x * right.x + left.y * right.y;
  912. };
  913. /**
  914. * Returns a new Vector2 equal to the normalized passed vector.
  915. */
  916. Vector2.Normalize = function (vector) {
  917. var newVector = vector.clone();
  918. newVector.normalize();
  919. return newVector;
  920. };
  921. /**
  922. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  923. */
  924. Vector2.Minimize = function (left, right) {
  925. var x = (left.x < right.x) ? left.x : right.x;
  926. var y = (left.y < right.y) ? left.y : right.y;
  927. return new Vector2(x, y);
  928. };
  929. /**
  930. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  931. */
  932. Vector2.Maximize = function (left, right) {
  933. var x = (left.x > right.x) ? left.x : right.x;
  934. var y = (left.y > right.y) ? left.y : right.y;
  935. return new Vector2(x, y);
  936. };
  937. /**
  938. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  939. */
  940. Vector2.Transform = function (vector, transformation) {
  941. var r = Vector2.Zero();
  942. Vector2.TransformToRef(vector, transformation, r);
  943. return r;
  944. };
  945. /**
  946. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  947. */
  948. Vector2.TransformToRef = function (vector, transformation, result) {
  949. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  950. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  951. result.x = x;
  952. result.y = y;
  953. };
  954. /**
  955. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  956. */
  957. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  958. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  959. var sign = a < 0 ? -1 : 1;
  960. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  961. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  962. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  963. };
  964. /**
  965. * Returns the distance (float) between the vectors "value1" and "value2".
  966. */
  967. Vector2.Distance = function (value1, value2) {
  968. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  969. };
  970. /**
  971. * Returns the squared distance (float) between the vectors "value1" and "value2".
  972. */
  973. Vector2.DistanceSquared = function (value1, value2) {
  974. var x = value1.x - value2.x;
  975. var y = value1.y - value2.y;
  976. return (x * x) + (y * y);
  977. };
  978. /**
  979. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  980. */
  981. Vector2.Center = function (value1, value2) {
  982. var center = value1.add(value2);
  983. center.scaleInPlace(0.5);
  984. return center;
  985. };
  986. /**
  987. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  988. */
  989. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  990. var l2 = Vector2.DistanceSquared(segA, segB);
  991. if (l2 === 0.0) {
  992. return Vector2.Distance(p, segA);
  993. }
  994. var v = segB.subtract(segA);
  995. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  996. var proj = segA.add(v.multiplyByFloats(t, t));
  997. return Vector2.Distance(p, proj);
  998. };
  999. return Vector2;
  1000. }());
  1001. BABYLON.Vector2 = Vector2;
  1002. var Vector3 = (function () {
  1003. /**
  1004. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1005. * A Vector3 is the main object used in 3D geometry.
  1006. * It can represent etiher the coordinates of a point the space, either a direction.
  1007. */
  1008. function Vector3(x, y, z) {
  1009. this.x = x;
  1010. this.y = y;
  1011. this.z = z;
  1012. }
  1013. /**
  1014. * Returns a string with the Vector3 coordinates.
  1015. */
  1016. Vector3.prototype.toString = function () {
  1017. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1018. };
  1019. /**
  1020. * Returns the string "Vector3"
  1021. */
  1022. Vector3.prototype.getClassName = function () {
  1023. return "Vector3";
  1024. };
  1025. /**
  1026. * Returns the Vector hash code.
  1027. */
  1028. Vector3.prototype.getHashCode = function () {
  1029. var hash = this.x || 0;
  1030. hash = (hash * 397) ^ (this.y || 0);
  1031. hash = (hash * 397) ^ (this.z || 0);
  1032. return hash;
  1033. };
  1034. // Operators
  1035. /**
  1036. * Returns a new array with three elements : the coordinates the Vector3.
  1037. */
  1038. Vector3.prototype.asArray = function () {
  1039. var result = [];
  1040. this.toArray(result, 0);
  1041. return result;
  1042. };
  1043. /**
  1044. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1045. * Returns the Vector3.
  1046. */
  1047. Vector3.prototype.toArray = function (array, index) {
  1048. if (index === void 0) { index = 0; }
  1049. array[index] = this.x;
  1050. array[index + 1] = this.y;
  1051. array[index + 2] = this.z;
  1052. return this;
  1053. };
  1054. /**
  1055. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1056. */
  1057. Vector3.prototype.toQuaternion = function () {
  1058. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1059. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1060. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1061. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1062. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1063. var cosy = Math.cos(this.y * 0.5);
  1064. var siny = Math.sin(this.y * 0.5);
  1065. result.x = coszMinusx * siny;
  1066. result.y = -sinzMinusx * siny;
  1067. result.z = sinxPlusz * cosy;
  1068. result.w = cosxPlusz * cosy;
  1069. return result;
  1070. };
  1071. /**
  1072. * Adds the passed vector to the current Vector3.
  1073. * Returns the updated Vector3.
  1074. */
  1075. Vector3.prototype.addInPlace = function (otherVector) {
  1076. this.x += otherVector.x;
  1077. this.y += otherVector.y;
  1078. this.z += otherVector.z;
  1079. return this;
  1080. };
  1081. /**
  1082. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1083. */
  1084. Vector3.prototype.add = function (otherVector) {
  1085. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1086. };
  1087. /**
  1088. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1089. * Returns the current Vector3.
  1090. */
  1091. Vector3.prototype.addToRef = function (otherVector, result) {
  1092. result.x = this.x + otherVector.x;
  1093. result.y = this.y + otherVector.y;
  1094. result.z = this.z + otherVector.z;
  1095. return this;
  1096. };
  1097. /**
  1098. * Subtract the passed vector from the current Vector3.
  1099. * Returns the updated Vector3.
  1100. */
  1101. Vector3.prototype.subtractInPlace = function (otherVector) {
  1102. this.x -= otherVector.x;
  1103. this.y -= otherVector.y;
  1104. this.z -= otherVector.z;
  1105. return this;
  1106. };
  1107. /**
  1108. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1109. */
  1110. Vector3.prototype.subtract = function (otherVector) {
  1111. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1112. };
  1113. /**
  1114. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1115. * Returns the current Vector3.
  1116. */
  1117. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1118. result.x = this.x - otherVector.x;
  1119. result.y = this.y - otherVector.y;
  1120. result.z = this.z - otherVector.z;
  1121. return this;
  1122. };
  1123. /**
  1124. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1125. */
  1126. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1127. return new Vector3(this.x - x, this.y - y, this.z - z);
  1128. };
  1129. /**
  1130. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1131. * Returns the current Vector3.
  1132. */
  1133. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1134. result.x = this.x - x;
  1135. result.y = this.y - y;
  1136. result.z = this.z - z;
  1137. return this;
  1138. };
  1139. /**
  1140. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1141. */
  1142. Vector3.prototype.negate = function () {
  1143. return new Vector3(-this.x, -this.y, -this.z);
  1144. };
  1145. /**
  1146. * Multiplies the Vector3 coordinates by the float "scale".
  1147. * Returns the updated Vector3.
  1148. */
  1149. Vector3.prototype.scaleInPlace = function (scale) {
  1150. this.x *= scale;
  1151. this.y *= scale;
  1152. this.z *= scale;
  1153. return this;
  1154. };
  1155. /**
  1156. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1157. */
  1158. Vector3.prototype.scale = function (scale) {
  1159. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1160. };
  1161. /**
  1162. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1163. * Returns the current Vector3.
  1164. */
  1165. Vector3.prototype.scaleToRef = function (scale, result) {
  1166. result.x = this.x * scale;
  1167. result.y = this.y * scale;
  1168. result.z = this.z * scale;
  1169. return this;
  1170. };
  1171. /**
  1172. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1173. */
  1174. Vector3.prototype.equals = function (otherVector) {
  1175. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1176. };
  1177. /**
  1178. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1179. */
  1180. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1181. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1182. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  1183. };
  1184. /**
  1185. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1186. */
  1187. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1188. return this.x === x && this.y === y && this.z === z;
  1189. };
  1190. /**
  1191. * Muliplies the current Vector3 coordinates by the passed ones.
  1192. * Returns the updated Vector3.
  1193. */
  1194. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1195. this.x *= otherVector.x;
  1196. this.y *= otherVector.y;
  1197. this.z *= otherVector.z;
  1198. return this;
  1199. };
  1200. /**
  1201. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1202. */
  1203. Vector3.prototype.multiply = function (otherVector) {
  1204. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1205. };
  1206. /**
  1207. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1208. * Returns the current Vector3.
  1209. */
  1210. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1211. result.x = this.x * otherVector.x;
  1212. result.y = this.y * otherVector.y;
  1213. result.z = this.z * otherVector.z;
  1214. return this;
  1215. };
  1216. /**
  1217. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1218. */
  1219. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1220. return new Vector3(this.x * x, this.y * y, this.z * z);
  1221. };
  1222. /**
  1223. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1224. */
  1225. Vector3.prototype.divide = function (otherVector) {
  1226. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1227. };
  1228. /**
  1229. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1230. * Returns the current Vector3.
  1231. */
  1232. Vector3.prototype.divideToRef = function (otherVector, result) {
  1233. result.x = this.x / otherVector.x;
  1234. result.y = this.y / otherVector.y;
  1235. result.z = this.z / otherVector.z;
  1236. return this;
  1237. };
  1238. /**
  1239. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1240. * Returns the updated Vector3.
  1241. */
  1242. Vector3.prototype.MinimizeInPlace = function (other) {
  1243. if (other.x < this.x)
  1244. this.x = other.x;
  1245. if (other.y < this.y)
  1246. this.y = other.y;
  1247. if (other.z < this.z)
  1248. this.z = other.z;
  1249. return this;
  1250. };
  1251. /**
  1252. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1253. * Returns the updated Vector3.
  1254. */
  1255. Vector3.prototype.MaximizeInPlace = function (other) {
  1256. if (other.x > this.x)
  1257. this.x = other.x;
  1258. if (other.y > this.y)
  1259. this.y = other.y;
  1260. if (other.z > this.z)
  1261. this.z = other.z;
  1262. return this;
  1263. };
  1264. // Properties
  1265. /**
  1266. * Returns the length of the Vector3 (float).
  1267. */
  1268. Vector3.prototype.length = function () {
  1269. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1270. };
  1271. /**
  1272. * Returns the squared length of the Vector3 (float).
  1273. */
  1274. Vector3.prototype.lengthSquared = function () {
  1275. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1276. };
  1277. // Methods
  1278. /**
  1279. * Normalize the current Vector3.
  1280. * Returns the updated Vector3.
  1281. */
  1282. Vector3.prototype.normalize = function () {
  1283. var len = this.length();
  1284. if (len === 0 || len === 1.0)
  1285. return this;
  1286. var num = 1.0 / len;
  1287. this.x *= num;
  1288. this.y *= num;
  1289. this.z *= num;
  1290. return this;
  1291. };
  1292. /**
  1293. * Returns a new Vector3 copied from the current Vector3.
  1294. */
  1295. Vector3.prototype.clone = function () {
  1296. return new Vector3(this.x, this.y, this.z);
  1297. };
  1298. /**
  1299. * Copies the passed vector coordinates to the current Vector3 ones.
  1300. * Returns the updated Vector3.
  1301. */
  1302. Vector3.prototype.copyFrom = function (source) {
  1303. this.x = source.x;
  1304. this.y = source.y;
  1305. this.z = source.z;
  1306. return this;
  1307. };
  1308. /**
  1309. * Copies the passed floats to the current Vector3 coordinates.
  1310. * Returns the updated Vector3.
  1311. */
  1312. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1313. this.x = x;
  1314. this.y = y;
  1315. this.z = z;
  1316. return this;
  1317. };
  1318. /**
  1319. * Copies the passed floats to the current Vector3 coordinates.
  1320. * Returns the updated Vector3.
  1321. */
  1322. Vector3.prototype.set = function (x, y, z) {
  1323. return this.copyFromFloats(x, y, z);
  1324. };
  1325. // Statics
  1326. /**
  1327. *
  1328. */
  1329. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1330. var d0 = Vector3.Dot(vector0, axis) - size;
  1331. var d1 = Vector3.Dot(vector1, axis) - size;
  1332. var s = d0 / (d0 - d1);
  1333. return s;
  1334. };
  1335. /**
  1336. * Returns a new Vector3 set from the index "offset" of the passed array.
  1337. */
  1338. Vector3.FromArray = function (array, offset) {
  1339. if (!offset) {
  1340. offset = 0;
  1341. }
  1342. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1343. };
  1344. /**
  1345. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1346. * This function is deprecated. Use FromArray instead.
  1347. */
  1348. Vector3.FromFloatArray = function (array, offset) {
  1349. return Vector3.FromArray(array, offset);
  1350. };
  1351. /**
  1352. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1353. */
  1354. Vector3.FromArrayToRef = function (array, offset, result) {
  1355. result.x = array[offset];
  1356. result.y = array[offset + 1];
  1357. result.z = array[offset + 2];
  1358. };
  1359. /**
  1360. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1361. * This function is deprecated. Use FromArrayToRef instead.
  1362. */
  1363. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1364. return Vector3.FromArrayToRef(array, offset, result);
  1365. };
  1366. /**
  1367. * Sets the passed vector "result" with the passed floats.
  1368. */
  1369. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1370. result.x = x;
  1371. result.y = y;
  1372. result.z = z;
  1373. };
  1374. /**
  1375. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1376. */
  1377. Vector3.Zero = function () {
  1378. return new Vector3(0.0, 0.0, 0.0);
  1379. };
  1380. /**
  1381. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1382. */
  1383. Vector3.Up = function () {
  1384. return new Vector3(0.0, 1.0, 0.0);
  1385. };
  1386. /**
  1387. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1388. */
  1389. Vector3.Forward = function () {
  1390. return new Vector3(0.0, 0.0, 1.0);
  1391. };
  1392. /**
  1393. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1394. */
  1395. Vector3.Right = function () {
  1396. return new Vector3(1.0, 0.0, 0.0);
  1397. };
  1398. /**
  1399. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1400. */
  1401. Vector3.Left = function () {
  1402. return new Vector3(-1.0, 0.0, 0.0);
  1403. };
  1404. /**
  1405. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1406. * This method computes tranformed coordinates only, not transformed direction vectors.
  1407. */
  1408. Vector3.TransformCoordinates = function (vector, transformation) {
  1409. var result = Vector3.Zero();
  1410. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1411. return result;
  1412. };
  1413. /**
  1414. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1415. * This method computes tranformed coordinates only, not transformed direction vectors.
  1416. */
  1417. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1418. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1419. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1420. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1421. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1422. result.x = x / w;
  1423. result.y = y / w;
  1424. result.z = z / w;
  1425. };
  1426. /**
  1427. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1428. * This method computes tranformed coordinates only, not transformed direction vectors.
  1429. */
  1430. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1431. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1432. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1433. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1434. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1435. result.x = rx / rw;
  1436. result.y = ry / rw;
  1437. result.z = rz / rw;
  1438. };
  1439. /**
  1440. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1441. * This methods computes transformed normalized direction vectors only.
  1442. */
  1443. Vector3.TransformNormal = function (vector, transformation) {
  1444. var result = Vector3.Zero();
  1445. Vector3.TransformNormalToRef(vector, transformation, result);
  1446. return result;
  1447. };
  1448. /**
  1449. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1450. * This methods computes transformed normalized direction vectors only.
  1451. */
  1452. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1453. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1454. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1455. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1456. result.x = x;
  1457. result.y = y;
  1458. result.z = z;
  1459. };
  1460. /**
  1461. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1462. * This methods computes transformed normalized direction vectors only.
  1463. */
  1464. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1465. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1466. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1467. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1468. };
  1469. /**
  1470. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1471. */
  1472. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1473. var squared = amount * amount;
  1474. var cubed = amount * squared;
  1475. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1476. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1477. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1478. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1479. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1480. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1481. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1482. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1483. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1484. return new Vector3(x, y, z);
  1485. };
  1486. /**
  1487. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max".
  1488. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1489. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1490. */
  1491. Vector3.Clamp = function (value, min, max) {
  1492. var x = value.x;
  1493. x = (x > max.x) ? max.x : x;
  1494. x = (x < min.x) ? min.x : x;
  1495. var y = value.y;
  1496. y = (y > max.y) ? max.y : y;
  1497. y = (y < min.y) ? min.y : y;
  1498. var z = value.z;
  1499. z = (z > max.z) ? max.z : z;
  1500. z = (z < min.z) ? min.z : z;
  1501. return new Vector3(x, y, z);
  1502. };
  1503. /**
  1504. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1505. */
  1506. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1507. var squared = amount * amount;
  1508. var cubed = amount * squared;
  1509. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1510. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1511. var part3 = (cubed - (2.0 * squared)) + amount;
  1512. var part4 = cubed - squared;
  1513. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1514. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1515. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1516. return new Vector3(x, y, z);
  1517. };
  1518. /**
  1519. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1520. */
  1521. Vector3.Lerp = function (start, end, amount) {
  1522. var result = new Vector3(0, 0, 0);
  1523. Vector3.LerpToRef(start, end, amount, result);
  1524. return result;
  1525. };
  1526. /**
  1527. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1528. */
  1529. Vector3.LerpToRef = function (start, end, amount, result) {
  1530. result.x = start.x + ((end.x - start.x) * amount);
  1531. result.y = start.y + ((end.y - start.y) * amount);
  1532. result.z = start.z + ((end.z - start.z) * amount);
  1533. };
  1534. /**
  1535. * Returns the dot product (float) between the vectors "left" and "right".
  1536. */
  1537. Vector3.Dot = function (left, right) {
  1538. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1539. };
  1540. /**
  1541. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1542. * The cross product is then orthogonal to both "left" and "right".
  1543. */
  1544. Vector3.Cross = function (left, right) {
  1545. var result = Vector3.Zero();
  1546. Vector3.CrossToRef(left, right, result);
  1547. return result;
  1548. };
  1549. /**
  1550. * Sets the passed vector "result" with the cross product of "left" and "right".
  1551. * The cross product is then orthogonal to both "left" and "right".
  1552. */
  1553. Vector3.CrossToRef = function (left, right, result) {
  1554. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1555. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1556. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1557. result.copyFrom(MathTmp.Vector3[0]);
  1558. };
  1559. /**
  1560. * Returns a new Vector3 as the normalization of the passed vector.
  1561. */
  1562. Vector3.Normalize = function (vector) {
  1563. var result = Vector3.Zero();
  1564. Vector3.NormalizeToRef(vector, result);
  1565. return result;
  1566. };
  1567. /**
  1568. * Sets the passed vector "result" with the normalization of the passed first vector.
  1569. */
  1570. Vector3.NormalizeToRef = function (vector, result) {
  1571. result.copyFrom(vector);
  1572. result.normalize();
  1573. };
  1574. Vector3.Project = function (vector, world, transform, viewport) {
  1575. var cw = viewport.width;
  1576. var ch = viewport.height;
  1577. var cx = viewport.x;
  1578. var cy = viewport.y;
  1579. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1580. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  1581. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1582. world.multiplyToRef(transform, matrix);
  1583. matrix.multiplyToRef(viewportMatrix, matrix);
  1584. return Vector3.TransformCoordinates(vector, matrix);
  1585. };
  1586. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1587. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1588. world.multiplyToRef(transform, matrix);
  1589. matrix.invert();
  1590. source.x = source.x / viewportWidth * 2 - 1;
  1591. source.y = -(source.y / viewportHeight * 2 - 1);
  1592. var vector = Vector3.TransformCoordinates(source, matrix);
  1593. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1594. if (MathTools.WithinEpsilon(num, 1.0)) {
  1595. vector = vector.scale(1.0 / num);
  1596. }
  1597. return vector;
  1598. };
  1599. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1600. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1601. world.multiplyToRef(view, matrix);
  1602. matrix.multiplyToRef(projection, matrix);
  1603. matrix.invert();
  1604. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1605. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1606. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1607. if (MathTools.WithinEpsilon(num, 1.0)) {
  1608. vector = vector.scale(1.0 / num);
  1609. }
  1610. return vector;
  1611. };
  1612. Vector3.Minimize = function (left, right) {
  1613. var min = left.clone();
  1614. min.MinimizeInPlace(right);
  1615. return min;
  1616. };
  1617. Vector3.Maximize = function (left, right) {
  1618. var max = left.clone();
  1619. max.MaximizeInPlace(right);
  1620. return max;
  1621. };
  1622. /**
  1623. * Returns the distance (float) between the vectors "value1" and "value2".
  1624. */
  1625. Vector3.Distance = function (value1, value2) {
  1626. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1627. };
  1628. /**
  1629. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1630. */
  1631. Vector3.DistanceSquared = function (value1, value2) {
  1632. var x = value1.x - value2.x;
  1633. var y = value1.y - value2.y;
  1634. var z = value1.z - value2.z;
  1635. return (x * x) + (y * y) + (z * z);
  1636. };
  1637. /**
  1638. * Returns a new Vector3 located at the center between "value1" and "value2".
  1639. */
  1640. Vector3.Center = function (value1, value2) {
  1641. var center = value1.add(value2);
  1642. center.scaleInPlace(0.5);
  1643. return center;
  1644. };
  1645. /**
  1646. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1647. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1648. * to something in order to rotate it from its local system to the given target system.
  1649. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1650. * Returns a new Vector3.
  1651. */
  1652. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1653. var rotation = Vector3.Zero();
  1654. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1655. return rotation;
  1656. };
  1657. /**
  1658. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1659. */
  1660. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1661. var quat = MathTmp.Quaternion[0];
  1662. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1663. quat.toEulerAnglesToRef(ref);
  1664. };
  1665. return Vector3;
  1666. }());
  1667. BABYLON.Vector3 = Vector3;
  1668. //Vector4 class created for EulerAngle class conversion to Quaternion
  1669. var Vector4 = (function () {
  1670. /**
  1671. * Creates a Vector4 object from the passed floats.
  1672. */
  1673. function Vector4(x, y, z, w) {
  1674. this.x = x;
  1675. this.y = y;
  1676. this.z = z;
  1677. this.w = w;
  1678. }
  1679. /**
  1680. * Returns the string with the Vector4 coordinates.
  1681. */
  1682. Vector4.prototype.toString = function () {
  1683. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1684. };
  1685. /**
  1686. * Returns the string "Vector4".
  1687. */
  1688. Vector4.prototype.getClassName = function () {
  1689. return "Vector4";
  1690. };
  1691. /**
  1692. * Returns the Vector4 hash code.
  1693. */
  1694. Vector4.prototype.getHashCode = function () {
  1695. var hash = this.x || 0;
  1696. hash = (hash * 397) ^ (this.y || 0);
  1697. hash = (hash * 397) ^ (this.z || 0);
  1698. hash = (hash * 397) ^ (this.w || 0);
  1699. return hash;
  1700. };
  1701. // Operators
  1702. /**
  1703. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1704. */
  1705. Vector4.prototype.asArray = function () {
  1706. var result = [];
  1707. this.toArray(result, 0);
  1708. return result;
  1709. };
  1710. /**
  1711. * Populates the passed array from the passed index with the Vector4 coordinates.
  1712. * Returns the Vector4.
  1713. */
  1714. Vector4.prototype.toArray = function (array, index) {
  1715. if (index === undefined) {
  1716. index = 0;
  1717. }
  1718. array[index] = this.x;
  1719. array[index + 1] = this.y;
  1720. array[index + 2] = this.z;
  1721. array[index + 3] = this.w;
  1722. return this;
  1723. };
  1724. /**
  1725. * Adds the passed vector to the current Vector4.
  1726. * Returns the updated Vector4.
  1727. */
  1728. Vector4.prototype.addInPlace = function (otherVector) {
  1729. this.x += otherVector.x;
  1730. this.y += otherVector.y;
  1731. this.z += otherVector.z;
  1732. this.w += otherVector.w;
  1733. return this;
  1734. };
  1735. /**
  1736. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1737. */
  1738. Vector4.prototype.add = function (otherVector) {
  1739. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1740. };
  1741. /**
  1742. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1743. * Returns the current Vector4.
  1744. */
  1745. Vector4.prototype.addToRef = function (otherVector, result) {
  1746. result.x = this.x + otherVector.x;
  1747. result.y = this.y + otherVector.y;
  1748. result.z = this.z + otherVector.z;
  1749. result.w = this.w + otherVector.w;
  1750. return this;
  1751. };
  1752. /**
  1753. * Subtract in place the passed vector from the current Vector4.
  1754. * Returns the updated Vector4.
  1755. */
  1756. Vector4.prototype.subtractInPlace = function (otherVector) {
  1757. this.x -= otherVector.x;
  1758. this.y -= otherVector.y;
  1759. this.z -= otherVector.z;
  1760. this.w -= otherVector.w;
  1761. return this;
  1762. };
  1763. /**
  1764. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1765. */
  1766. Vector4.prototype.subtract = function (otherVector) {
  1767. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1768. };
  1769. /**
  1770. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1771. * Returns the current Vector4.
  1772. */
  1773. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1774. result.x = this.x - otherVector.x;
  1775. result.y = this.y - otherVector.y;
  1776. result.z = this.z - otherVector.z;
  1777. result.w = this.w - otherVector.w;
  1778. return this;
  1779. };
  1780. /**
  1781. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1782. */
  1783. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1784. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1785. };
  1786. /**
  1787. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1788. * Returns the current Vector4.
  1789. */
  1790. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1791. result.x = this.x - x;
  1792. result.y = this.y - y;
  1793. result.z = this.z - z;
  1794. result.w = this.w - w;
  1795. return this;
  1796. };
  1797. /**
  1798. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1799. */
  1800. Vector4.prototype.negate = function () {
  1801. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1802. };
  1803. /**
  1804. * Multiplies the current Vector4 coordinates by scale (float).
  1805. * Returns the updated Vector4.
  1806. */
  1807. Vector4.prototype.scaleInPlace = function (scale) {
  1808. this.x *= scale;
  1809. this.y *= scale;
  1810. this.z *= scale;
  1811. this.w *= scale;
  1812. return this;
  1813. };
  1814. /**
  1815. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1816. */
  1817. Vector4.prototype.scale = function (scale) {
  1818. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1819. };
  1820. /**
  1821. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1822. * Returns the current Vector4.
  1823. */
  1824. Vector4.prototype.scaleToRef = function (scale, result) {
  1825. result.x = this.x * scale;
  1826. result.y = this.y * scale;
  1827. result.z = this.z * scale;
  1828. result.w = this.w * scale;
  1829. return this;
  1830. };
  1831. /**
  1832. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1833. */
  1834. Vector4.prototype.equals = function (otherVector) {
  1835. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1836. };
  1837. /**
  1838. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1839. */
  1840. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1841. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1842. return otherVector
  1843. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1844. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1845. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1846. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1847. };
  1848. /**
  1849. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1850. */
  1851. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1852. return this.x === x && this.y === y && this.z === z && this.w === w;
  1853. };
  1854. /**
  1855. * Multiplies in place the current Vector4 by the passed one.
  1856. * Returns the updated Vector4.
  1857. */
  1858. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1859. this.x *= otherVector.x;
  1860. this.y *= otherVector.y;
  1861. this.z *= otherVector.z;
  1862. this.w *= otherVector.w;
  1863. return this;
  1864. };
  1865. /**
  1866. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  1867. */
  1868. Vector4.prototype.multiply = function (otherVector) {
  1869. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1870. };
  1871. /**
  1872. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  1873. * Returns the current Vector4.
  1874. */
  1875. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1876. result.x = this.x * otherVector.x;
  1877. result.y = this.y * otherVector.y;
  1878. result.z = this.z * otherVector.z;
  1879. result.w = this.w * otherVector.w;
  1880. return this;
  1881. };
  1882. /**
  1883. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  1884. */
  1885. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1886. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1887. };
  1888. /**
  1889. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  1890. */
  1891. Vector4.prototype.divide = function (otherVector) {
  1892. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1893. };
  1894. /**
  1895. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  1896. * Returns the current Vector4.
  1897. */
  1898. Vector4.prototype.divideToRef = function (otherVector, result) {
  1899. result.x = this.x / otherVector.x;
  1900. result.y = this.y / otherVector.y;
  1901. result.z = this.z / otherVector.z;
  1902. result.w = this.w / otherVector.w;
  1903. return this;
  1904. };
  1905. /**
  1906. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  1907. */
  1908. Vector4.prototype.MinimizeInPlace = function (other) {
  1909. if (other.x < this.x)
  1910. this.x = other.x;
  1911. if (other.y < this.y)
  1912. this.y = other.y;
  1913. if (other.z < this.z)
  1914. this.z = other.z;
  1915. if (other.w < this.w)
  1916. this.w = other.w;
  1917. return this;
  1918. };
  1919. /**
  1920. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  1921. */
  1922. Vector4.prototype.MaximizeInPlace = function (other) {
  1923. if (other.x > this.x)
  1924. this.x = other.x;
  1925. if (other.y > this.y)
  1926. this.y = other.y;
  1927. if (other.z > this.z)
  1928. this.z = other.z;
  1929. if (other.w > this.w)
  1930. this.w = other.w;
  1931. return this;
  1932. };
  1933. // Properties
  1934. /**
  1935. * Returns the Vector4 length (float).
  1936. */
  1937. Vector4.prototype.length = function () {
  1938. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1939. };
  1940. /**
  1941. * Returns the Vector4 squared length (float).
  1942. */
  1943. Vector4.prototype.lengthSquared = function () {
  1944. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1945. };
  1946. // Methods
  1947. /**
  1948. * Normalizes in place the Vector4.
  1949. * Returns the updated Vector4.
  1950. */
  1951. Vector4.prototype.normalize = function () {
  1952. var len = this.length();
  1953. if (len === 0)
  1954. return this;
  1955. var num = 1.0 / len;
  1956. this.x *= num;
  1957. this.y *= num;
  1958. this.z *= num;
  1959. this.w *= num;
  1960. return this;
  1961. };
  1962. /**
  1963. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  1964. */
  1965. Vector4.prototype.toVector3 = function () {
  1966. return new Vector3(this.x, this.y, this.z);
  1967. };
  1968. /**
  1969. * Returns a new Vector4 copied from the current one.
  1970. */
  1971. Vector4.prototype.clone = function () {
  1972. return new Vector4(this.x, this.y, this.z, this.w);
  1973. };
  1974. /**
  1975. * Updates the current Vector4 with the passed one coordinates.
  1976. * Returns the updated Vector4.
  1977. */
  1978. Vector4.prototype.copyFrom = function (source) {
  1979. this.x = source.x;
  1980. this.y = source.y;
  1981. this.z = source.z;
  1982. this.w = source.w;
  1983. return this;
  1984. };
  1985. /**
  1986. * Updates the current Vector4 coordinates with the passed floats.
  1987. * Returns the updated Vector4.
  1988. */
  1989. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1990. this.x = x;
  1991. this.y = y;
  1992. this.z = z;
  1993. this.w = w;
  1994. return this;
  1995. };
  1996. /**
  1997. * Updates the current Vector4 coordinates with the passed floats.
  1998. * Returns the updated Vector4.
  1999. */
  2000. Vector4.prototype.set = function (x, y, z, w) {
  2001. return this.copyFromFloats(x, y, z, w);
  2002. };
  2003. // Statics
  2004. /**
  2005. * Returns a new Vector4 set from the starting index of the passed array.
  2006. */
  2007. Vector4.FromArray = function (array, offset) {
  2008. if (!offset) {
  2009. offset = 0;
  2010. }
  2011. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2012. };
  2013. /**
  2014. * Updates the passed vector "result" from the starting index of the passed array.
  2015. */
  2016. Vector4.FromArrayToRef = function (array, offset, result) {
  2017. result.x = array[offset];
  2018. result.y = array[offset + 1];
  2019. result.z = array[offset + 2];
  2020. result.w = array[offset + 3];
  2021. };
  2022. /**
  2023. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2024. */
  2025. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2026. Vector4.FromArrayToRef(array, offset, result);
  2027. };
  2028. /**
  2029. * Updates the passed vector "result" coordinates from the passed floats.
  2030. */
  2031. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2032. result.x = x;
  2033. result.y = y;
  2034. result.z = z;
  2035. result.w = w;
  2036. };
  2037. /**
  2038. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2039. */
  2040. Vector4.Zero = function () {
  2041. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2042. };
  2043. /**
  2044. * Returns a new normalized Vector4 from the passed one.
  2045. */
  2046. Vector4.Normalize = function (vector) {
  2047. var result = Vector4.Zero();
  2048. Vector4.NormalizeToRef(vector, result);
  2049. return result;
  2050. };
  2051. /**
  2052. * Updates the passed vector "result" from the normalization of the passed one.
  2053. */
  2054. Vector4.NormalizeToRef = function (vector, result) {
  2055. result.copyFrom(vector);
  2056. result.normalize();
  2057. };
  2058. Vector4.Minimize = function (left, right) {
  2059. var min = left.clone();
  2060. min.MinimizeInPlace(right);
  2061. return min;
  2062. };
  2063. Vector4.Maximize = function (left, right) {
  2064. var max = left.clone();
  2065. max.MaximizeInPlace(right);
  2066. return max;
  2067. };
  2068. /**
  2069. * Returns the distance (float) between the vectors "value1" and "value2".
  2070. */
  2071. Vector4.Distance = function (value1, value2) {
  2072. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2073. };
  2074. /**
  2075. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2076. */
  2077. Vector4.DistanceSquared = function (value1, value2) {
  2078. var x = value1.x - value2.x;
  2079. var y = value1.y - value2.y;
  2080. var z = value1.z - value2.z;
  2081. var w = value1.w - value2.w;
  2082. return (x * x) + (y * y) + (z * z) + (w * w);
  2083. };
  2084. /**
  2085. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2086. */
  2087. Vector4.Center = function (value1, value2) {
  2088. var center = value1.add(value2);
  2089. center.scaleInPlace(0.5);
  2090. return center;
  2091. };
  2092. /**
  2093. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2094. * This methods computes transformed normalized direction vectors only.
  2095. */
  2096. Vector4.TransformNormal = function (vector, transformation) {
  2097. var result = Vector4.Zero();
  2098. Vector4.TransformNormalToRef(vector, transformation, result);
  2099. return result;
  2100. };
  2101. /**
  2102. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2103. * This methods computes transformed normalized direction vectors only.
  2104. */
  2105. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2106. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2107. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2108. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2109. result.x = x;
  2110. result.y = y;
  2111. result.z = z;
  2112. result.w = vector.w;
  2113. };
  2114. /**
  2115. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2116. * This methods computes transformed normalized direction vectors only.
  2117. */
  2118. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2119. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2120. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2121. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2122. result.w = w;
  2123. };
  2124. return Vector4;
  2125. }());
  2126. BABYLON.Vector4 = Vector4;
  2127. var Size = (function () {
  2128. /**
  2129. * Creates a Size object from the passed width and height (floats).
  2130. */
  2131. function Size(width, height) {
  2132. this.width = width;
  2133. this.height = height;
  2134. }
  2135. // Returns a string with the Size width and height.
  2136. Size.prototype.toString = function () {
  2137. return "{W: " + this.width + ", H: " + this.height + "}";
  2138. };
  2139. /**
  2140. * Returns the string "Size"
  2141. */
  2142. Size.prototype.getClassName = function () {
  2143. return "Size";
  2144. };
  2145. /**
  2146. * Returns the Size hash code.
  2147. */
  2148. Size.prototype.getHashCode = function () {
  2149. var hash = this.width || 0;
  2150. hash = (hash * 397) ^ (this.height || 0);
  2151. return hash;
  2152. };
  2153. /**
  2154. * Updates the current size from the passed one.
  2155. * Returns the updated Size.
  2156. */
  2157. Size.prototype.copyFrom = function (src) {
  2158. this.width = src.width;
  2159. this.height = src.height;
  2160. };
  2161. /**
  2162. * Updates in place the current Size from the passed floats.
  2163. * Returns the updated Size.
  2164. */
  2165. Size.prototype.copyFromFloats = function (width, height) {
  2166. this.width = width;
  2167. this.height = height;
  2168. return this;
  2169. };
  2170. /**
  2171. * Updates in place the current Size from the passed floats.
  2172. * Returns the updated Size.
  2173. */
  2174. Size.prototype.set = function (width, height) {
  2175. return this.copyFromFloats(width, height);
  2176. };
  2177. /**
  2178. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2179. */
  2180. Size.prototype.multiplyByFloats = function (w, h) {
  2181. return new Size(this.width * w, this.height * h);
  2182. };
  2183. /**
  2184. * Returns a new Size copied from the passed one.
  2185. */
  2186. Size.prototype.clone = function () {
  2187. return new Size(this.width, this.height);
  2188. };
  2189. /**
  2190. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2191. */
  2192. Size.prototype.equals = function (other) {
  2193. if (!other) {
  2194. return false;
  2195. }
  2196. return (this.width === other.width) && (this.height === other.height);
  2197. };
  2198. Object.defineProperty(Size.prototype, "surface", {
  2199. /**
  2200. * Returns the surface of the Size : width * height (float).
  2201. */
  2202. get: function () {
  2203. return this.width * this.height;
  2204. },
  2205. enumerable: true,
  2206. configurable: true
  2207. });
  2208. /**
  2209. * Returns a new Size set to (0.0, 0.0)
  2210. */
  2211. Size.Zero = function () {
  2212. return new Size(0.0, 0.0);
  2213. };
  2214. /**
  2215. * Returns a new Size set as the addition result of the current Size and the passed one.
  2216. */
  2217. Size.prototype.add = function (otherSize) {
  2218. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2219. return r;
  2220. };
  2221. /**
  2222. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2223. */
  2224. Size.prototype.subtract = function (otherSize) {
  2225. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2226. return r;
  2227. };
  2228. /**
  2229. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2230. */
  2231. Size.Lerp = function (start, end, amount) {
  2232. var w = start.width + ((end.width - start.width) * amount);
  2233. var h = start.height + ((end.height - start.height) * amount);
  2234. return new Size(w, h);
  2235. };
  2236. return Size;
  2237. }());
  2238. BABYLON.Size = Size;
  2239. var Quaternion = (function () {
  2240. /**
  2241. * Creates a new Quaternion from the passed floats.
  2242. */
  2243. function Quaternion(x, y, z, w) {
  2244. if (x === void 0) { x = 0.0; }
  2245. if (y === void 0) { y = 0.0; }
  2246. if (z === void 0) { z = 0.0; }
  2247. if (w === void 0) { w = 1.0; }
  2248. this.x = x;
  2249. this.y = y;
  2250. this.z = z;
  2251. this.w = w;
  2252. }
  2253. /**
  2254. * Returns a string with the Quaternion coordinates.
  2255. */
  2256. Quaternion.prototype.toString = function () {
  2257. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2258. };
  2259. /**
  2260. * Returns the string "Quaternion".
  2261. */
  2262. Quaternion.prototype.getClassName = function () {
  2263. return "Quaternion";
  2264. };
  2265. /**
  2266. * Returns the Quaternion hash code.
  2267. */
  2268. Quaternion.prototype.getHashCode = function () {
  2269. var hash = this.x || 0;
  2270. hash = (hash * 397) ^ (this.y || 0);
  2271. hash = (hash * 397) ^ (this.z || 0);
  2272. hash = (hash * 397) ^ (this.w || 0);
  2273. return hash;
  2274. };
  2275. /**
  2276. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2277. */
  2278. Quaternion.prototype.asArray = function () {
  2279. return [this.x, this.y, this.z, this.w];
  2280. };
  2281. /**
  2282. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2283. */
  2284. Quaternion.prototype.equals = function (otherQuaternion) {
  2285. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2286. };
  2287. /**
  2288. * Returns a new Quaternion copied from the current one.
  2289. */
  2290. Quaternion.prototype.clone = function () {
  2291. return new Quaternion(this.x, this.y, this.z, this.w);
  2292. };
  2293. /**
  2294. * Updates the current Quaternion from the passed one coordinates.
  2295. * Returns the updated Quaterion.
  2296. */
  2297. Quaternion.prototype.copyFrom = function (other) {
  2298. this.x = other.x;
  2299. this.y = other.y;
  2300. this.z = other.z;
  2301. this.w = other.w;
  2302. return this;
  2303. };
  2304. /**
  2305. * Updates the current Quaternion from the passed float coordinates.
  2306. * Returns the updated Quaterion.
  2307. */
  2308. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2309. this.x = x;
  2310. this.y = y;
  2311. this.z = z;
  2312. this.w = w;
  2313. return this;
  2314. };
  2315. /**
  2316. * Updates the current Quaternion from the passed float coordinates.
  2317. * Returns the updated Quaterion.
  2318. */
  2319. Quaternion.prototype.set = function (x, y, z, w) {
  2320. return this.copyFromFloats(x, y, z, w);
  2321. };
  2322. /**
  2323. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2324. */
  2325. Quaternion.prototype.add = function (other) {
  2326. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2327. };
  2328. /**
  2329. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2330. */
  2331. Quaternion.prototype.subtract = function (other) {
  2332. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2333. };
  2334. /**
  2335. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2336. */
  2337. Quaternion.prototype.scale = function (value) {
  2338. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2339. };
  2340. /**
  2341. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2342. */
  2343. Quaternion.prototype.multiply = function (q1) {
  2344. var result = new Quaternion(0, 0, 0, 1.0);
  2345. this.multiplyToRef(q1, result);
  2346. return result;
  2347. };
  2348. /**
  2349. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2350. * Returns the current Quaternion.
  2351. */
  2352. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2353. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2354. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2355. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2356. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2357. result.copyFromFloats(x, y, z, w);
  2358. return this;
  2359. };
  2360. /**
  2361. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2362. * Returns the updated Quaternion.
  2363. */
  2364. Quaternion.prototype.multiplyInPlace = function (q1) {
  2365. this.multiplyToRef(q1, this);
  2366. return this;
  2367. };
  2368. /**
  2369. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2370. * Returns the current Quaternion.
  2371. */
  2372. Quaternion.prototype.conjugateToRef = function (ref) {
  2373. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2374. return this;
  2375. };
  2376. /**
  2377. * Conjugates in place the current Quaternion.
  2378. * Returns the updated Quaternion.
  2379. */
  2380. Quaternion.prototype.conjugateInPlace = function () {
  2381. this.x *= -1;
  2382. this.y *= -1;
  2383. this.z *= -1;
  2384. return this;
  2385. };
  2386. /**
  2387. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2388. */
  2389. Quaternion.prototype.conjugate = function () {
  2390. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2391. return result;
  2392. };
  2393. /**
  2394. * Returns the Quaternion length (float).
  2395. */
  2396. Quaternion.prototype.length = function () {
  2397. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2398. };
  2399. /**
  2400. * Normalize in place the current Quaternion.
  2401. * Returns the updated Quaternion.
  2402. */
  2403. Quaternion.prototype.normalize = function () {
  2404. var length = 1.0 / this.length();
  2405. this.x *= length;
  2406. this.y *= length;
  2407. this.z *= length;
  2408. this.w *= length;
  2409. return this;
  2410. };
  2411. /**
  2412. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2413. */
  2414. Quaternion.prototype.toEulerAngles = function (order) {
  2415. if (order === void 0) { order = "YZX"; }
  2416. var result = Vector3.Zero();
  2417. this.toEulerAnglesToRef(result, order);
  2418. return result;
  2419. };
  2420. /**
  2421. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2422. * Returns the current Quaternion.
  2423. */
  2424. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2425. if (order === void 0) { order = "YZX"; }
  2426. var qz = this.z;
  2427. var qx = this.x;
  2428. var qy = this.y;
  2429. var qw = this.w;
  2430. var sqw = qw * qw;
  2431. var sqz = qz * qz;
  2432. var sqx = qx * qx;
  2433. var sqy = qy * qy;
  2434. var zAxisY = qy * qz - qx * qw;
  2435. var limit = .4999999;
  2436. if (zAxisY < -limit) {
  2437. result.y = 2 * Math.atan2(qy, qw);
  2438. result.x = Math.PI / 2;
  2439. result.z = 0;
  2440. }
  2441. else if (zAxisY > limit) {
  2442. result.y = 2 * Math.atan2(qy, qw);
  2443. result.x = -Math.PI / 2;
  2444. result.z = 0;
  2445. }
  2446. else {
  2447. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2448. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2449. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2450. }
  2451. return this;
  2452. };
  2453. /**
  2454. * Updates the passed rotation matrix with the current Quaternion values.
  2455. * Returns the current Quaternion.
  2456. */
  2457. Quaternion.prototype.toRotationMatrix = function (result) {
  2458. var xx = this.x * this.x;
  2459. var yy = this.y * this.y;
  2460. var zz = this.z * this.z;
  2461. var xy = this.x * this.y;
  2462. var zw = this.z * this.w;
  2463. var zx = this.z * this.x;
  2464. var yw = this.y * this.w;
  2465. var yz = this.y * this.z;
  2466. var xw = this.x * this.w;
  2467. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2468. result.m[1] = 2.0 * (xy + zw);
  2469. result.m[2] = 2.0 * (zx - yw);
  2470. result.m[3] = 0;
  2471. result.m[4] = 2.0 * (xy - zw);
  2472. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2473. result.m[6] = 2.0 * (yz + xw);
  2474. result.m[7] = 0;
  2475. result.m[8] = 2.0 * (zx + yw);
  2476. result.m[9] = 2.0 * (yz - xw);
  2477. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2478. result.m[11] = 0;
  2479. result.m[12] = 0;
  2480. result.m[13] = 0;
  2481. result.m[14] = 0;
  2482. result.m[15] = 1.0;
  2483. result._markAsUpdated();
  2484. return this;
  2485. };
  2486. /**
  2487. * Updates the current Quaternion from the passed rotation matrix values.
  2488. * Returns the updated Quaternion.
  2489. */
  2490. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2491. Quaternion.FromRotationMatrixToRef(matrix, this);
  2492. return this;
  2493. };
  2494. // Statics
  2495. /**
  2496. * Returns a new Quaternion set from the passed rotation matrix values.
  2497. */
  2498. Quaternion.FromRotationMatrix = function (matrix) {
  2499. var result = new Quaternion();
  2500. Quaternion.FromRotationMatrixToRef(matrix, result);
  2501. return result;
  2502. };
  2503. /**
  2504. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2505. */
  2506. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2507. var data = matrix.m;
  2508. var m11 = data[0], m12 = data[4], m13 = data[8];
  2509. var m21 = data[1], m22 = data[5], m23 = data[9];
  2510. var m31 = data[2], m32 = data[6], m33 = data[10];
  2511. var trace = m11 + m22 + m33;
  2512. var s;
  2513. if (trace > 0) {
  2514. s = 0.5 / Math.sqrt(trace + 1.0);
  2515. result.w = 0.25 / s;
  2516. result.x = (m32 - m23) * s;
  2517. result.y = (m13 - m31) * s;
  2518. result.z = (m21 - m12) * s;
  2519. }
  2520. else if (m11 > m22 && m11 > m33) {
  2521. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2522. result.w = (m32 - m23) / s;
  2523. result.x = 0.25 * s;
  2524. result.y = (m12 + m21) / s;
  2525. result.z = (m13 + m31) / s;
  2526. }
  2527. else if (m22 > m33) {
  2528. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2529. result.w = (m13 - m31) / s;
  2530. result.x = (m12 + m21) / s;
  2531. result.y = 0.25 * s;
  2532. result.z = (m23 + m32) / s;
  2533. }
  2534. else {
  2535. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2536. result.w = (m21 - m12) / s;
  2537. result.x = (m13 + m31) / s;
  2538. result.y = (m23 + m32) / s;
  2539. result.z = 0.25 * s;
  2540. }
  2541. };
  2542. /**
  2543. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2544. */
  2545. Quaternion.Zero = function () {
  2546. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2547. };
  2548. /**
  2549. * Returns a new Quaternion as the inverted current Quaternion.
  2550. */
  2551. Quaternion.Inverse = function (q) {
  2552. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2553. };
  2554. /**
  2555. * Returns the identity Quaternion.
  2556. */
  2557. Quaternion.Identity = function () {
  2558. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2559. };
  2560. Quaternion.IsIdentity = function (quaternion) {
  2561. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2562. };
  2563. /**
  2564. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2565. */
  2566. Quaternion.RotationAxis = function (axis, angle) {
  2567. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2568. };
  2569. /**
  2570. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2571. */
  2572. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2573. var sin = Math.sin(angle / 2);
  2574. axis.normalize();
  2575. result.w = Math.cos(angle / 2);
  2576. result.x = axis.x * sin;
  2577. result.y = axis.y * sin;
  2578. result.z = axis.z * sin;
  2579. return result;
  2580. };
  2581. /**
  2582. * Retuns a new Quaternion set from the starting index of the passed array.
  2583. */
  2584. Quaternion.FromArray = function (array, offset) {
  2585. if (!offset) {
  2586. offset = 0;
  2587. }
  2588. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2589. };
  2590. /**
  2591. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2592. */
  2593. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2594. var q = new Quaternion();
  2595. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2596. return q;
  2597. };
  2598. /**
  2599. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2600. */
  2601. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2602. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2603. var halfRoll = roll * 0.5;
  2604. var halfPitch = pitch * 0.5;
  2605. var halfYaw = yaw * 0.5;
  2606. var sinRoll = Math.sin(halfRoll);
  2607. var cosRoll = Math.cos(halfRoll);
  2608. var sinPitch = Math.sin(halfPitch);
  2609. var cosPitch = Math.cos(halfPitch);
  2610. var sinYaw = Math.sin(halfYaw);
  2611. var cosYaw = Math.cos(halfYaw);
  2612. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2613. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2614. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2615. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2616. };
  2617. /**
  2618. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2619. */
  2620. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2621. var result = new Quaternion();
  2622. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2623. return result;
  2624. };
  2625. /**
  2626. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2627. */
  2628. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2629. // Produces a quaternion from Euler angles in the z-x-z orientation
  2630. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2631. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2632. var halfBeta = beta * 0.5;
  2633. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2634. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2635. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2636. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2637. };
  2638. /**
  2639. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2640. * cf to Vector3.RotationFromAxis() documentation.
  2641. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2642. */
  2643. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2644. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2645. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2646. return quat;
  2647. };
  2648. /**
  2649. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2650. * cf to Vector3.RotationFromAxis() documentation.
  2651. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2652. */
  2653. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2654. var rotMat = MathTmp.Matrix[0];
  2655. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2656. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2657. };
  2658. Quaternion.Slerp = function (left, right, amount) {
  2659. var result = Quaternion.Identity();
  2660. Quaternion.SlerpToRef(left, right, amount, result);
  2661. return result;
  2662. };
  2663. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2664. var num2;
  2665. var num3;
  2666. var num = amount;
  2667. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2668. var flag = false;
  2669. if (num4 < 0) {
  2670. flag = true;
  2671. num4 = -num4;
  2672. }
  2673. if (num4 > 0.999999) {
  2674. num3 = 1 - num;
  2675. num2 = flag ? -num : num;
  2676. }
  2677. else {
  2678. var num5 = Math.acos(num4);
  2679. var num6 = (1.0 / Math.sin(num5));
  2680. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2681. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2682. }
  2683. result.x = (num3 * left.x) + (num2 * right.x);
  2684. result.y = (num3 * left.y) + (num2 * right.y);
  2685. result.z = (num3 * left.z) + (num2 * right.z);
  2686. result.w = (num3 * left.w) + (num2 * right.w);
  2687. };
  2688. /**
  2689. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2690. */
  2691. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2692. var squared = amount * amount;
  2693. var cubed = amount * squared;
  2694. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2695. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2696. var part3 = (cubed - (2.0 * squared)) + amount;
  2697. var part4 = cubed - squared;
  2698. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2699. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2700. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2701. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2702. return new Quaternion(x, y, z, w);
  2703. };
  2704. return Quaternion;
  2705. }());
  2706. BABYLON.Quaternion = Quaternion;
  2707. var Matrix = (function () {
  2708. function Matrix() {
  2709. this.m = new Float32Array(16);
  2710. this._markAsUpdated();
  2711. }
  2712. Matrix.prototype._markAsUpdated = function () {
  2713. this.updateFlag = Matrix._updateFlagSeed++;
  2714. };
  2715. // Properties
  2716. /**
  2717. * Boolean : True is the matrix is the identity matrix
  2718. */
  2719. Matrix.prototype.isIdentity = function () {
  2720. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  2721. return false;
  2722. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2723. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2724. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2725. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  2726. return false;
  2727. return true;
  2728. };
  2729. /**
  2730. * Returns the matrix determinant (float).
  2731. */
  2732. Matrix.prototype.determinant = function () {
  2733. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2734. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2735. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2736. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2737. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2738. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2739. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2740. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2741. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2742. };
  2743. // Methods
  2744. /**
  2745. * Returns the matrix underlying array.
  2746. */
  2747. Matrix.prototype.toArray = function () {
  2748. return this.m;
  2749. };
  2750. /**
  2751. * Returns the matrix underlying array.
  2752. */
  2753. Matrix.prototype.asArray = function () {
  2754. return this.toArray();
  2755. };
  2756. /**
  2757. * Inverts in place the Matrix.
  2758. * Returns the Matrix inverted.
  2759. */
  2760. Matrix.prototype.invert = function () {
  2761. this.invertToRef(this);
  2762. return this;
  2763. };
  2764. /**
  2765. * Sets all the matrix elements to zero.
  2766. * Returns the Matrix.
  2767. */
  2768. Matrix.prototype.reset = function () {
  2769. for (var index = 0; index < 16; index++) {
  2770. this.m[index] = 0.0;
  2771. }
  2772. this._markAsUpdated();
  2773. return this;
  2774. };
  2775. /**
  2776. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2777. */
  2778. Matrix.prototype.add = function (other) {
  2779. var result = new Matrix();
  2780. this.addToRef(other, result);
  2781. return result;
  2782. };
  2783. /**
  2784. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2785. * Returns the Matrix.
  2786. */
  2787. Matrix.prototype.addToRef = function (other, result) {
  2788. for (var index = 0; index < 16; index++) {
  2789. result.m[index] = this.m[index] + other.m[index];
  2790. }
  2791. result._markAsUpdated();
  2792. return this;
  2793. };
  2794. /**
  2795. * Adds in place the passed matrix to the current Matrix.
  2796. * Returns the updated Matrix.
  2797. */
  2798. Matrix.prototype.addToSelf = function (other) {
  2799. for (var index = 0; index < 16; index++) {
  2800. this.m[index] += other.m[index];
  2801. }
  2802. this._markAsUpdated();
  2803. return this;
  2804. };
  2805. /**
  2806. * Sets the passed matrix with the current inverted Matrix.
  2807. * Returns the unmodified current Matrix.
  2808. */
  2809. Matrix.prototype.invertToRef = function (other) {
  2810. var l1 = this.m[0];
  2811. var l2 = this.m[1];
  2812. var l3 = this.m[2];
  2813. var l4 = this.m[3];
  2814. var l5 = this.m[4];
  2815. var l6 = this.m[5];
  2816. var l7 = this.m[6];
  2817. var l8 = this.m[7];
  2818. var l9 = this.m[8];
  2819. var l10 = this.m[9];
  2820. var l11 = this.m[10];
  2821. var l12 = this.m[11];
  2822. var l13 = this.m[12];
  2823. var l14 = this.m[13];
  2824. var l15 = this.m[14];
  2825. var l16 = this.m[15];
  2826. var l17 = (l11 * l16) - (l12 * l15);
  2827. var l18 = (l10 * l16) - (l12 * l14);
  2828. var l19 = (l10 * l15) - (l11 * l14);
  2829. var l20 = (l9 * l16) - (l12 * l13);
  2830. var l21 = (l9 * l15) - (l11 * l13);
  2831. var l22 = (l9 * l14) - (l10 * l13);
  2832. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2833. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2834. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2835. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2836. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2837. var l28 = (l7 * l16) - (l8 * l15);
  2838. var l29 = (l6 * l16) - (l8 * l14);
  2839. var l30 = (l6 * l15) - (l7 * l14);
  2840. var l31 = (l5 * l16) - (l8 * l13);
  2841. var l32 = (l5 * l15) - (l7 * l13);
  2842. var l33 = (l5 * l14) - (l6 * l13);
  2843. var l34 = (l7 * l12) - (l8 * l11);
  2844. var l35 = (l6 * l12) - (l8 * l10);
  2845. var l36 = (l6 * l11) - (l7 * l10);
  2846. var l37 = (l5 * l12) - (l8 * l9);
  2847. var l38 = (l5 * l11) - (l7 * l9);
  2848. var l39 = (l5 * l10) - (l6 * l9);
  2849. other.m[0] = l23 * l27;
  2850. other.m[4] = l24 * l27;
  2851. other.m[8] = l25 * l27;
  2852. other.m[12] = l26 * l27;
  2853. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  2854. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  2855. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  2856. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  2857. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  2858. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  2859. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  2860. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  2861. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  2862. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  2863. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  2864. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  2865. other._markAsUpdated();
  2866. return this;
  2867. };
  2868. /**
  2869. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  2870. * Returns the updated Matrix.
  2871. */
  2872. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  2873. this.m[12] = x;
  2874. this.m[13] = y;
  2875. this.m[14] = z;
  2876. this._markAsUpdated();
  2877. return this;
  2878. };
  2879. /**
  2880. * Inserts the translation vector in the current Matrix.
  2881. * Returns the updated Matrix.
  2882. */
  2883. Matrix.prototype.setTranslation = function (vector3) {
  2884. this.m[12] = vector3.x;
  2885. this.m[13] = vector3.y;
  2886. this.m[14] = vector3.z;
  2887. this._markAsUpdated();
  2888. return this;
  2889. };
  2890. /**
  2891. * Returns a new Vector3 as the extracted translation from the Matrix.
  2892. */
  2893. Matrix.prototype.getTranslation = function () {
  2894. return new Vector3(this.m[12], this.m[13], this.m[14]);
  2895. };
  2896. /**
  2897. * Fill a Vector3 with the extracted translation from the Matrix.
  2898. */
  2899. Matrix.prototype.getTranslationToRef = function (result) {
  2900. result.x = this.m[12];
  2901. result.y = this.m[13];
  2902. result.z = this.m[14];
  2903. return this;
  2904. };
  2905. /**
  2906. * Remove rotation and scaling part from the Matrix.
  2907. * Returns the updated Matrix.
  2908. */
  2909. Matrix.prototype.removeRotationAndScaling = function () {
  2910. this.setRowFromFloats(0, 1, 0, 0, 0);
  2911. this.setRowFromFloats(1, 0, 1, 0, 0);
  2912. this.setRowFromFloats(2, 0, 0, 1, 0);
  2913. return this;
  2914. };
  2915. /**
  2916. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  2917. */
  2918. Matrix.prototype.multiply = function (other) {
  2919. var result = new Matrix();
  2920. this.multiplyToRef(other, result);
  2921. return result;
  2922. };
  2923. /**
  2924. * Updates the current Matrix from the passed one values.
  2925. * Returns the updated Matrix.
  2926. */
  2927. Matrix.prototype.copyFrom = function (other) {
  2928. for (var index = 0; index < 16; index++) {
  2929. this.m[index] = other.m[index];
  2930. }
  2931. this._markAsUpdated();
  2932. return this;
  2933. };
  2934. /**
  2935. * Populates the passed array from the starting index with the Matrix values.
  2936. * Returns the Matrix.
  2937. */
  2938. Matrix.prototype.copyToArray = function (array, offset) {
  2939. if (offset === void 0) { offset = 0; }
  2940. for (var index = 0; index < 16; index++) {
  2941. array[offset + index] = this.m[index];
  2942. }
  2943. return this;
  2944. };
  2945. /**
  2946. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  2947. */
  2948. Matrix.prototype.multiplyToRef = function (other, result) {
  2949. this.multiplyToArray(other, result.m, 0);
  2950. result._markAsUpdated();
  2951. return this;
  2952. };
  2953. /**
  2954. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  2955. */
  2956. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  2957. var tm0 = this.m[0];
  2958. var tm1 = this.m[1];
  2959. var tm2 = this.m[2];
  2960. var tm3 = this.m[3];
  2961. var tm4 = this.m[4];
  2962. var tm5 = this.m[5];
  2963. var tm6 = this.m[6];
  2964. var tm7 = this.m[7];
  2965. var tm8 = this.m[8];
  2966. var tm9 = this.m[9];
  2967. var tm10 = this.m[10];
  2968. var tm11 = this.m[11];
  2969. var tm12 = this.m[12];
  2970. var tm13 = this.m[13];
  2971. var tm14 = this.m[14];
  2972. var tm15 = this.m[15];
  2973. var om0 = other.m[0];
  2974. var om1 = other.m[1];
  2975. var om2 = other.m[2];
  2976. var om3 = other.m[3];
  2977. var om4 = other.m[4];
  2978. var om5 = other.m[5];
  2979. var om6 = other.m[6];
  2980. var om7 = other.m[7];
  2981. var om8 = other.m[8];
  2982. var om9 = other.m[9];
  2983. var om10 = other.m[10];
  2984. var om11 = other.m[11];
  2985. var om12 = other.m[12];
  2986. var om13 = other.m[13];
  2987. var om14 = other.m[14];
  2988. var om15 = other.m[15];
  2989. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  2990. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  2991. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  2992. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  2993. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  2994. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  2995. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  2996. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  2997. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  2998. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  2999. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3000. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3001. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3002. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3003. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3004. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3005. return this;
  3006. };
  3007. /**
  3008. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3009. */
  3010. Matrix.prototype.equals = function (value) {
  3011. return value &&
  3012. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3013. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3014. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3015. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3016. };
  3017. /**
  3018. * Returns a new Matrix from the current Matrix.
  3019. */
  3020. Matrix.prototype.clone = function () {
  3021. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  3022. };
  3023. /**
  3024. * Returns the string "Matrix"
  3025. */
  3026. Matrix.prototype.getClassName = function () {
  3027. return "Matrix";
  3028. };
  3029. /**
  3030. * Returns the Matrix hash code.
  3031. */
  3032. Matrix.prototype.getHashCode = function () {
  3033. var hash = this.m[0] || 0;
  3034. for (var i = 1; i < 16; i++) {
  3035. hash = (hash * 397) ^ (this.m[i] || 0);
  3036. }
  3037. return hash;
  3038. };
  3039. /**
  3040. * Decomposes the current Matrix into :
  3041. * - a scale vector3 passed as a reference to update,
  3042. * - a rotation quaternion passed as a reference to update,
  3043. * - a translation vector3 passed as a reference to update.
  3044. * Returns the boolean `true`.
  3045. */
  3046. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3047. translation.x = this.m[12];
  3048. translation.y = this.m[13];
  3049. translation.z = this.m[14];
  3050. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  3051. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  3052. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  3053. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3054. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3055. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3056. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3057. rotation.x = 0;
  3058. rotation.y = 0;
  3059. rotation.z = 0;
  3060. rotation.w = 1;
  3061. return false;
  3062. }
  3063. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  3064. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3065. return true;
  3066. };
  3067. /**
  3068. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3069. */
  3070. Matrix.prototype.getRotationMatrix = function () {
  3071. var result = Matrix.Identity();
  3072. this.getRotationMatrixToRef(result);
  3073. return result;
  3074. };
  3075. /**
  3076. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3077. * Returns the current Matrix.
  3078. */
  3079. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3080. var m = this.m;
  3081. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3082. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3083. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3084. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3085. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3086. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3087. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  3088. return this;
  3089. };
  3090. // Statics
  3091. /**
  3092. * Returns a new Matrix set from the starting index of the passed array.
  3093. */
  3094. Matrix.FromArray = function (array, offset) {
  3095. var result = new Matrix();
  3096. if (!offset) {
  3097. offset = 0;
  3098. }
  3099. Matrix.FromArrayToRef(array, offset, result);
  3100. return result;
  3101. };
  3102. /**
  3103. * Sets the passed "result" matrix from the starting index of the passed array.
  3104. */
  3105. Matrix.FromArrayToRef = function (array, offset, result) {
  3106. for (var index = 0; index < 16; index++) {
  3107. result.m[index] = array[index + offset];
  3108. }
  3109. result._markAsUpdated();
  3110. };
  3111. /**
  3112. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3113. */
  3114. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3115. for (var index = 0; index < 16; index++) {
  3116. result.m[index] = array[index + offset] * scale;
  3117. }
  3118. result._markAsUpdated();
  3119. };
  3120. /**
  3121. * Sets the passed matrix "result" with the 16 passed floats.
  3122. */
  3123. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3124. result.m[0] = initialM11;
  3125. result.m[1] = initialM12;
  3126. result.m[2] = initialM13;
  3127. result.m[3] = initialM14;
  3128. result.m[4] = initialM21;
  3129. result.m[5] = initialM22;
  3130. result.m[6] = initialM23;
  3131. result.m[7] = initialM24;
  3132. result.m[8] = initialM31;
  3133. result.m[9] = initialM32;
  3134. result.m[10] = initialM33;
  3135. result.m[11] = initialM34;
  3136. result.m[12] = initialM41;
  3137. result.m[13] = initialM42;
  3138. result.m[14] = initialM43;
  3139. result.m[15] = initialM44;
  3140. result._markAsUpdated();
  3141. };
  3142. /**
  3143. * Returns the index-th row of the current matrix as a new Vector4.
  3144. */
  3145. Matrix.prototype.getRow = function (index) {
  3146. if (index < 0 || index > 3) {
  3147. return null;
  3148. }
  3149. var i = index * 4;
  3150. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3151. };
  3152. /**
  3153. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3154. * Returns the updated Matrix.
  3155. */
  3156. Matrix.prototype.setRow = function (index, row) {
  3157. if (index < 0 || index > 3) {
  3158. return this;
  3159. }
  3160. var i = index * 4;
  3161. this.m[i + 0] = row.x;
  3162. this.m[i + 1] = row.y;
  3163. this.m[i + 2] = row.z;
  3164. this.m[i + 3] = row.w;
  3165. this._markAsUpdated();
  3166. return this;
  3167. };
  3168. /**
  3169. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3170. * Returns the updated Matrix.
  3171. */
  3172. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3173. if (index < 0 || index > 3) {
  3174. return this;
  3175. }
  3176. var i = index * 4;
  3177. this.m[i + 0] = x;
  3178. this.m[i + 1] = y;
  3179. this.m[i + 2] = z;
  3180. this.m[i + 3] = w;
  3181. this._markAsUpdated();
  3182. return this;
  3183. };
  3184. /**
  3185. * Returns a new Matrix set from the 16 passed floats.
  3186. */
  3187. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3188. var result = new Matrix();
  3189. result.m[0] = initialM11;
  3190. result.m[1] = initialM12;
  3191. result.m[2] = initialM13;
  3192. result.m[3] = initialM14;
  3193. result.m[4] = initialM21;
  3194. result.m[5] = initialM22;
  3195. result.m[6] = initialM23;
  3196. result.m[7] = initialM24;
  3197. result.m[8] = initialM31;
  3198. result.m[9] = initialM32;
  3199. result.m[10] = initialM33;
  3200. result.m[11] = initialM34;
  3201. result.m[12] = initialM41;
  3202. result.m[13] = initialM42;
  3203. result.m[14] = initialM43;
  3204. result.m[15] = initialM44;
  3205. return result;
  3206. };
  3207. /**
  3208. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3209. */
  3210. Matrix.Compose = function (scale, rotation, translation) {
  3211. var result = Matrix.Identity();
  3212. Matrix.ComposeToRef(scale, rotation, translation, result);
  3213. return result;
  3214. };
  3215. /**
  3216. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3217. */
  3218. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3219. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3220. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3221. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3222. result.setTranslation(translation);
  3223. };
  3224. /**
  3225. * Returns a new indentity Matrix.
  3226. */
  3227. Matrix.Identity = function () {
  3228. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  3229. };
  3230. /**
  3231. * Sets the passed "result" as an identity matrix.
  3232. */
  3233. Matrix.IdentityToRef = function (result) {
  3234. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  3235. };
  3236. /**
  3237. * Returns a new zero Matrix.
  3238. */
  3239. Matrix.Zero = function () {
  3240. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  3241. };
  3242. /**
  3243. * Returns a new rotation matrix for "angle" radians around the X axis.
  3244. */
  3245. Matrix.RotationX = function (angle) {
  3246. var result = new Matrix();
  3247. Matrix.RotationXToRef(angle, result);
  3248. return result;
  3249. };
  3250. /**
  3251. * Returns a new Matrix as the passed inverted one.
  3252. */
  3253. Matrix.Invert = function (source) {
  3254. var result = new Matrix();
  3255. source.invertToRef(result);
  3256. return result;
  3257. };
  3258. /**
  3259. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3260. */
  3261. Matrix.RotationXToRef = function (angle, result) {
  3262. var s = Math.sin(angle);
  3263. var c = Math.cos(angle);
  3264. result.m[0] = 1.0;
  3265. result.m[15] = 1.0;
  3266. result.m[5] = c;
  3267. result.m[10] = c;
  3268. result.m[9] = -s;
  3269. result.m[6] = s;
  3270. result.m[1] = 0.0;
  3271. result.m[2] = 0.0;
  3272. result.m[3] = 0.0;
  3273. result.m[4] = 0.0;
  3274. result.m[7] = 0.0;
  3275. result.m[8] = 0.0;
  3276. result.m[11] = 0.0;
  3277. result.m[12] = 0.0;
  3278. result.m[13] = 0.0;
  3279. result.m[14] = 0.0;
  3280. result._markAsUpdated();
  3281. };
  3282. /**
  3283. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3284. */
  3285. Matrix.RotationY = function (angle) {
  3286. var result = new Matrix();
  3287. Matrix.RotationYToRef(angle, result);
  3288. return result;
  3289. };
  3290. /**
  3291. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3292. */
  3293. Matrix.RotationYToRef = function (angle, result) {
  3294. var s = Math.sin(angle);
  3295. var c = Math.cos(angle);
  3296. result.m[5] = 1.0;
  3297. result.m[15] = 1.0;
  3298. result.m[0] = c;
  3299. result.m[2] = -s;
  3300. result.m[8] = s;
  3301. result.m[10] = c;
  3302. result.m[1] = 0.0;
  3303. result.m[3] = 0.0;
  3304. result.m[4] = 0.0;
  3305. result.m[6] = 0.0;
  3306. result.m[7] = 0.0;
  3307. result.m[9] = 0.0;
  3308. result.m[11] = 0.0;
  3309. result.m[12] = 0.0;
  3310. result.m[13] = 0.0;
  3311. result.m[14] = 0.0;
  3312. result._markAsUpdated();
  3313. };
  3314. /**
  3315. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3316. */
  3317. Matrix.RotationZ = function (angle) {
  3318. var result = new Matrix();
  3319. Matrix.RotationZToRef(angle, result);
  3320. return result;
  3321. };
  3322. /**
  3323. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3324. */
  3325. Matrix.RotationZToRef = function (angle, result) {
  3326. var s = Math.sin(angle);
  3327. var c = Math.cos(angle);
  3328. result.m[10] = 1.0;
  3329. result.m[15] = 1.0;
  3330. result.m[0] = c;
  3331. result.m[1] = s;
  3332. result.m[4] = -s;
  3333. result.m[5] = c;
  3334. result.m[2] = 0.0;
  3335. result.m[3] = 0.0;
  3336. result.m[6] = 0.0;
  3337. result.m[7] = 0.0;
  3338. result.m[8] = 0.0;
  3339. result.m[9] = 0.0;
  3340. result.m[11] = 0.0;
  3341. result.m[12] = 0.0;
  3342. result.m[13] = 0.0;
  3343. result.m[14] = 0.0;
  3344. result._markAsUpdated();
  3345. };
  3346. /**
  3347. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3348. */
  3349. Matrix.RotationAxis = function (axis, angle) {
  3350. var result = Matrix.Zero();
  3351. Matrix.RotationAxisToRef(axis, angle, result);
  3352. return result;
  3353. };
  3354. /**
  3355. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3356. */
  3357. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3358. var s = Math.sin(-angle);
  3359. var c = Math.cos(-angle);
  3360. var c1 = 1 - c;
  3361. axis.normalize();
  3362. result.m[0] = (axis.x * axis.x) * c1 + c;
  3363. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3364. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3365. result.m[3] = 0.0;
  3366. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3367. result.m[5] = (axis.y * axis.y) * c1 + c;
  3368. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3369. result.m[7] = 0.0;
  3370. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3371. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3372. result.m[10] = (axis.z * axis.z) * c1 + c;
  3373. result.m[11] = 0.0;
  3374. result.m[15] = 1.0;
  3375. result._markAsUpdated();
  3376. };
  3377. /**
  3378. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3379. */
  3380. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3381. var result = new Matrix();
  3382. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3383. return result;
  3384. };
  3385. /**
  3386. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3387. */
  3388. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3389. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3390. this._tempQuaternion.toRotationMatrix(result);
  3391. };
  3392. /**
  3393. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3394. */
  3395. Matrix.Scaling = function (x, y, z) {
  3396. var result = Matrix.Zero();
  3397. Matrix.ScalingToRef(x, y, z, result);
  3398. return result;
  3399. };
  3400. /**
  3401. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3402. */
  3403. Matrix.ScalingToRef = function (x, y, z, result) {
  3404. result.m[0] = x;
  3405. result.m[1] = 0.0;
  3406. result.m[2] = 0.0;
  3407. result.m[3] = 0.0;
  3408. result.m[4] = 0.0;
  3409. result.m[5] = y;
  3410. result.m[6] = 0.0;
  3411. result.m[7] = 0.0;
  3412. result.m[8] = 0.0;
  3413. result.m[9] = 0.0;
  3414. result.m[10] = z;
  3415. result.m[11] = 0.0;
  3416. result.m[12] = 0.0;
  3417. result.m[13] = 0.0;
  3418. result.m[14] = 0.0;
  3419. result.m[15] = 1.0;
  3420. result._markAsUpdated();
  3421. };
  3422. /**
  3423. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3424. */
  3425. Matrix.Translation = function (x, y, z) {
  3426. var result = Matrix.Identity();
  3427. Matrix.TranslationToRef(x, y, z, result);
  3428. return result;
  3429. };
  3430. /**
  3431. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3432. */
  3433. Matrix.TranslationToRef = function (x, y, z, result) {
  3434. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  3435. };
  3436. /**
  3437. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3438. */
  3439. Matrix.Lerp = function (startValue, endValue, gradient) {
  3440. var result = Matrix.Zero();
  3441. for (var index = 0; index < 16; index++) {
  3442. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3443. }
  3444. result._markAsUpdated();
  3445. return result;
  3446. };
  3447. /**
  3448. * Returns a new Matrix whose values are computed by :
  3449. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3450. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3451. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3452. */
  3453. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3454. var startScale = new Vector3(0, 0, 0);
  3455. var startRotation = new Quaternion();
  3456. var startTranslation = new Vector3(0, 0, 0);
  3457. startValue.decompose(startScale, startRotation, startTranslation);
  3458. var endScale = new Vector3(0, 0, 0);
  3459. var endRotation = new Quaternion();
  3460. var endTranslation = new Vector3(0, 0, 0);
  3461. endValue.decompose(endScale, endRotation, endTranslation);
  3462. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3463. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3464. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3465. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3466. };
  3467. /**
  3468. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3469. * This methods works for a Left-Handed system.
  3470. */
  3471. Matrix.LookAtLH = function (eye, target, up) {
  3472. var result = Matrix.Zero();
  3473. Matrix.LookAtLHToRef(eye, target, up, result);
  3474. return result;
  3475. };
  3476. /**
  3477. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3478. * This methods works for a Left-Handed system.
  3479. */
  3480. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3481. // Z axis
  3482. target.subtractToRef(eye, this._zAxis);
  3483. this._zAxis.normalize();
  3484. // X axis
  3485. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3486. if (this._xAxis.lengthSquared() === 0) {
  3487. this._xAxis.x = 1.0;
  3488. }
  3489. else {
  3490. this._xAxis.normalize();
  3491. }
  3492. // Y axis
  3493. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3494. this._yAxis.normalize();
  3495. // Eye angles
  3496. var ex = -Vector3.Dot(this._xAxis, eye);
  3497. var ey = -Vector3.Dot(this._yAxis, eye);
  3498. var ez = -Vector3.Dot(this._zAxis, eye);
  3499. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  3500. };
  3501. /**
  3502. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3503. * This methods works for a Right-Handed system.
  3504. */
  3505. Matrix.LookAtRH = function (eye, target, up) {
  3506. var result = Matrix.Zero();
  3507. Matrix.LookAtRHToRef(eye, target, up, result);
  3508. return result;
  3509. };
  3510. /**
  3511. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3512. * This methods works for a Left-Handed system.
  3513. */
  3514. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3515. // Z axis
  3516. eye.subtractToRef(target, this._zAxis);
  3517. this._zAxis.normalize();
  3518. // X axis
  3519. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3520. if (this._xAxis.lengthSquared() === 0) {
  3521. this._xAxis.x = 1.0;
  3522. }
  3523. else {
  3524. this._xAxis.normalize();
  3525. }
  3526. // Y axis
  3527. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3528. this._yAxis.normalize();
  3529. // Eye angles
  3530. var ex = -Vector3.Dot(this._xAxis, eye);
  3531. var ey = -Vector3.Dot(this._yAxis, eye);
  3532. var ez = -Vector3.Dot(this._zAxis, eye);
  3533. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  3534. };
  3535. /**
  3536. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3537. */
  3538. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3539. var matrix = Matrix.Zero();
  3540. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3541. return matrix;
  3542. };
  3543. /**
  3544. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3545. */
  3546. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3547. var n = znear;
  3548. var f = zfar;
  3549. var a = 2.0 / width;
  3550. var b = 2.0 / height;
  3551. var c = 2.0 / (f - n);
  3552. var d = -(f + n) / (f - n);
  3553. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  3554. };
  3555. /**
  3556. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3557. */
  3558. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3559. var matrix = Matrix.Zero();
  3560. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3561. return matrix;
  3562. };
  3563. /**
  3564. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3565. */
  3566. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3567. var n = znear;
  3568. var f = zfar;
  3569. var a = 2.0 / (right - left);
  3570. var b = 2.0 / (top - bottom);
  3571. var c = 2.0 / (f - n);
  3572. var d = -(f + n) / (f - n);
  3573. var i0 = (left + right) / (left - right);
  3574. var i1 = (top + bottom) / (bottom - top);
  3575. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  3576. };
  3577. /**
  3578. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3579. */
  3580. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3581. var matrix = Matrix.Zero();
  3582. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3583. return matrix;
  3584. };
  3585. /**
  3586. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3587. */
  3588. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3589. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3590. result.m[10] *= -1.0;
  3591. };
  3592. /**
  3593. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3594. */
  3595. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3596. var matrix = Matrix.Zero();
  3597. var n = znear;
  3598. var f = zfar;
  3599. var a = 2.0 * n / width;
  3600. var b = 2.0 * n / height;
  3601. var c = (f + n) / (f - n);
  3602. var d = -2.0 * f * n / (f - n);
  3603. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  3604. return matrix;
  3605. };
  3606. /**
  3607. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3608. */
  3609. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3610. var matrix = Matrix.Zero();
  3611. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3612. return matrix;
  3613. };
  3614. /**
  3615. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3616. */
  3617. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3618. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3619. var n = znear;
  3620. var f = zfar;
  3621. var t = 1.0 / (Math.tan(fov * 0.5));
  3622. var a = isVerticalFovFixed ? (t / aspect) : t;
  3623. var b = isVerticalFovFixed ? t : (t * aspect);
  3624. var c = (f + n) / (f - n);
  3625. var d = -2.0 * f * n / (f - n);
  3626. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  3627. };
  3628. /**
  3629. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3630. */
  3631. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3632. var matrix = Matrix.Zero();
  3633. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3634. return matrix;
  3635. };
  3636. /**
  3637. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3638. */
  3639. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3640. //alternatively this could be expressed as:
  3641. // m = PerspectiveFovLHToRef
  3642. // m[10] *= -1.0;
  3643. // m[11] *= -1.0;
  3644. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3645. var n = znear;
  3646. var f = zfar;
  3647. var t = 1.0 / (Math.tan(fov * 0.5));
  3648. var a = isVerticalFovFixed ? (t / aspect) : t;
  3649. var b = isVerticalFovFixed ? t : (t * aspect);
  3650. var c = -(f + n) / (f - n);
  3651. var d = -2 * f * n / (f - n);
  3652. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  3653. };
  3654. /**
  3655. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3656. */
  3657. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3658. if (rightHanded === void 0) { rightHanded = false; }
  3659. var rightHandedFactor = rightHanded ? -1 : 1;
  3660. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3661. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3662. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3663. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3664. var xScale = 2.0 / (leftTan + rightTan);
  3665. var yScale = 2.0 / (upTan + downTan);
  3666. result.m[0] = xScale;
  3667. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3668. result.m[5] = yScale;
  3669. result.m[6] = result.m[7] = 0.0;
  3670. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3671. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3672. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3673. result.m[10] = -zfar / (znear - zfar);
  3674. result.m[11] = 1.0 * rightHandedFactor;
  3675. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3676. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3677. // result.m[14] = (znear * zfar) / (znear - zfar);
  3678. result._markAsUpdated();
  3679. };
  3680. /**
  3681. * Returns the final transformation matrix : world * view * projection * viewport
  3682. */
  3683. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3684. var cw = viewport.width;
  3685. var ch = viewport.height;
  3686. var cx = viewport.x;
  3687. var cy = viewport.y;
  3688. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  3689. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3690. };
  3691. /**
  3692. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3693. */
  3694. Matrix.GetAsMatrix2x2 = function (matrix) {
  3695. return new Float32Array([
  3696. matrix.m[0], matrix.m[1],
  3697. matrix.m[4], matrix.m[5]
  3698. ]);
  3699. };
  3700. /**
  3701. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3702. */
  3703. Matrix.GetAsMatrix3x3 = function (matrix) {
  3704. return new Float32Array([
  3705. matrix.m[0], matrix.m[1], matrix.m[2],
  3706. matrix.m[4], matrix.m[5], matrix.m[6],
  3707. matrix.m[8], matrix.m[9], matrix.m[10]
  3708. ]);
  3709. };
  3710. /**
  3711. * Compute the transpose of the passed Matrix.
  3712. * Returns a new Matrix.
  3713. */
  3714. Matrix.Transpose = function (matrix) {
  3715. var result = new Matrix();
  3716. result.m[0] = matrix.m[0];
  3717. result.m[1] = matrix.m[4];
  3718. result.m[2] = matrix.m[8];
  3719. result.m[3] = matrix.m[12];
  3720. result.m[4] = matrix.m[1];
  3721. result.m[5] = matrix.m[5];
  3722. result.m[6] = matrix.m[9];
  3723. result.m[7] = matrix.m[13];
  3724. result.m[8] = matrix.m[2];
  3725. result.m[9] = matrix.m[6];
  3726. result.m[10] = matrix.m[10];
  3727. result.m[11] = matrix.m[14];
  3728. result.m[12] = matrix.m[3];
  3729. result.m[13] = matrix.m[7];
  3730. result.m[14] = matrix.m[11];
  3731. result.m[15] = matrix.m[15];
  3732. return result;
  3733. };
  3734. /**
  3735. * Returns a new Matrix as the reflection matrix across the passed plane.
  3736. */
  3737. Matrix.Reflection = function (plane) {
  3738. var matrix = new Matrix();
  3739. Matrix.ReflectionToRef(plane, matrix);
  3740. return matrix;
  3741. };
  3742. /**
  3743. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3744. */
  3745. Matrix.ReflectionToRef = function (plane, result) {
  3746. plane.normalize();
  3747. var x = plane.normal.x;
  3748. var y = plane.normal.y;
  3749. var z = plane.normal.z;
  3750. var temp = -2 * x;
  3751. var temp2 = -2 * y;
  3752. var temp3 = -2 * z;
  3753. result.m[0] = (temp * x) + 1;
  3754. result.m[1] = temp2 * x;
  3755. result.m[2] = temp3 * x;
  3756. result.m[3] = 0.0;
  3757. result.m[4] = temp * y;
  3758. result.m[5] = (temp2 * y) + 1;
  3759. result.m[6] = temp3 * y;
  3760. result.m[7] = 0.0;
  3761. result.m[8] = temp * z;
  3762. result.m[9] = temp2 * z;
  3763. result.m[10] = (temp3 * z) + 1;
  3764. result.m[11] = 0.0;
  3765. result.m[12] = temp * plane.d;
  3766. result.m[13] = temp2 * plane.d;
  3767. result.m[14] = temp3 * plane.d;
  3768. result.m[15] = 1.0;
  3769. result._markAsUpdated();
  3770. };
  3771. /**
  3772. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3773. */
  3774. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3775. result.m[0] = xaxis.x;
  3776. result.m[1] = xaxis.y;
  3777. result.m[2] = xaxis.z;
  3778. result.m[3] = 0.0;
  3779. result.m[4] = yaxis.x;
  3780. result.m[5] = yaxis.y;
  3781. result.m[6] = yaxis.z;
  3782. result.m[7] = 0.0;
  3783. result.m[8] = zaxis.x;
  3784. result.m[9] = zaxis.y;
  3785. result.m[10] = zaxis.z;
  3786. result.m[11] = 0.0;
  3787. result.m[12] = 0.0;
  3788. result.m[13] = 0.0;
  3789. result.m[14] = 0.0;
  3790. result.m[15] = 1.0;
  3791. result._markAsUpdated();
  3792. };
  3793. /**
  3794. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3795. */
  3796. Matrix.FromQuaternionToRef = function (quat, result) {
  3797. var xx = quat.x * quat.x;
  3798. var yy = quat.y * quat.y;
  3799. var zz = quat.z * quat.z;
  3800. var xy = quat.x * quat.y;
  3801. var zw = quat.z * quat.w;
  3802. var zx = quat.z * quat.x;
  3803. var yw = quat.y * quat.w;
  3804. var yz = quat.y * quat.z;
  3805. var xw = quat.x * quat.w;
  3806. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3807. result.m[1] = 2.0 * (xy + zw);
  3808. result.m[2] = 2.0 * (zx - yw);
  3809. result.m[3] = 0.0;
  3810. result.m[4] = 2.0 * (xy - zw);
  3811. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3812. result.m[6] = 2.0 * (yz + xw);
  3813. result.m[7] = 0.0;
  3814. result.m[8] = 2.0 * (zx + yw);
  3815. result.m[9] = 2.0 * (yz - xw);
  3816. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3817. result.m[11] = 0.0;
  3818. result.m[12] = 0.0;
  3819. result.m[13] = 0.0;
  3820. result.m[14] = 0.0;
  3821. result.m[15] = 1.0;
  3822. result._markAsUpdated();
  3823. };
  3824. return Matrix;
  3825. }());
  3826. Matrix._tempQuaternion = new Quaternion();
  3827. Matrix._xAxis = Vector3.Zero();
  3828. Matrix._yAxis = Vector3.Zero();
  3829. Matrix._zAxis = Vector3.Zero();
  3830. Matrix._updateFlagSeed = 0;
  3831. BABYLON.Matrix = Matrix;
  3832. var Plane = (function () {
  3833. /**
  3834. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3835. */
  3836. function Plane(a, b, c, d) {
  3837. this.normal = new Vector3(a, b, c);
  3838. this.d = d;
  3839. }
  3840. /**
  3841. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  3842. */
  3843. Plane.prototype.asArray = function () {
  3844. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  3845. };
  3846. // Methods
  3847. /**
  3848. * Returns a new plane copied from the current Plane.
  3849. */
  3850. Plane.prototype.clone = function () {
  3851. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  3852. };
  3853. /**
  3854. * Returns the string "Plane".
  3855. */
  3856. Plane.prototype.getClassName = function () {
  3857. return "Plane";
  3858. };
  3859. /**
  3860. * Returns the Plane hash code.
  3861. */
  3862. Plane.prototype.getHashCode = function () {
  3863. var hash = this.normal.getHashCode();
  3864. hash = (hash * 397) ^ (this.d || 0);
  3865. return hash;
  3866. };
  3867. /**
  3868. * Normalize the current Plane in place.
  3869. * Returns the updated Plane.
  3870. */
  3871. Plane.prototype.normalize = function () {
  3872. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  3873. var magnitude = 0.0;
  3874. if (norm !== 0) {
  3875. magnitude = 1.0 / norm;
  3876. }
  3877. this.normal.x *= magnitude;
  3878. this.normal.y *= magnitude;
  3879. this.normal.z *= magnitude;
  3880. this.d *= magnitude;
  3881. return this;
  3882. };
  3883. /**
  3884. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  3885. */
  3886. Plane.prototype.transform = function (transformation) {
  3887. var transposedMatrix = Matrix.Transpose(transformation);
  3888. var x = this.normal.x;
  3889. var y = this.normal.y;
  3890. var z = this.normal.z;
  3891. var d = this.d;
  3892. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  3893. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  3894. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  3895. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  3896. return new Plane(normalX, normalY, normalZ, finalD);
  3897. };
  3898. /**
  3899. * Returns the dot product (float) of the point coordinates and the plane normal.
  3900. */
  3901. Plane.prototype.dotCoordinate = function (point) {
  3902. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  3903. };
  3904. /**
  3905. * Updates the current Plane from the plane defined by the three passed points.
  3906. * Returns the updated Plane.
  3907. */
  3908. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  3909. var x1 = point2.x - point1.x;
  3910. var y1 = point2.y - point1.y;
  3911. var z1 = point2.z - point1.z;
  3912. var x2 = point3.x - point1.x;
  3913. var y2 = point3.y - point1.y;
  3914. var z2 = point3.z - point1.z;
  3915. var yz = (y1 * z2) - (z1 * y2);
  3916. var xz = (z1 * x2) - (x1 * z2);
  3917. var xy = (x1 * y2) - (y1 * x2);
  3918. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  3919. var invPyth;
  3920. if (pyth !== 0) {
  3921. invPyth = 1.0 / pyth;
  3922. }
  3923. else {
  3924. invPyth = 0.0;
  3925. }
  3926. this.normal.x = yz * invPyth;
  3927. this.normal.y = xz * invPyth;
  3928. this.normal.z = xy * invPyth;
  3929. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  3930. return this;
  3931. };
  3932. /**
  3933. * Boolean : True is the vector "direction" is the same side than the plane normal.
  3934. */
  3935. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  3936. var dot = Vector3.Dot(this.normal, direction);
  3937. return (dot <= epsilon);
  3938. };
  3939. /**
  3940. * Returns the signed distance (float) from the passed point to the Plane.
  3941. */
  3942. Plane.prototype.signedDistanceTo = function (point) {
  3943. return Vector3.Dot(point, this.normal) + this.d;
  3944. };
  3945. // Statics
  3946. /**
  3947. * Returns a new Plane from the passed array.
  3948. */
  3949. Plane.FromArray = function (array) {
  3950. return new Plane(array[0], array[1], array[2], array[3]);
  3951. };
  3952. /**
  3953. * Returns a new Plane defined by the three passed points.
  3954. */
  3955. Plane.FromPoints = function (point1, point2, point3) {
  3956. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3957. result.copyFromPoints(point1, point2, point3);
  3958. return result;
  3959. };
  3960. /**
  3961. * Returns a new Plane the normal vector to this plane at the passed origin point.
  3962. * Note : the vector "normal" is updated because normalized.
  3963. */
  3964. Plane.FromPositionAndNormal = function (origin, normal) {
  3965. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3966. normal.normalize();
  3967. result.normal = normal;
  3968. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3969. return result;
  3970. };
  3971. /**
  3972. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  3973. */
  3974. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  3975. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3976. return Vector3.Dot(point, normal) + d;
  3977. };
  3978. return Plane;
  3979. }());
  3980. BABYLON.Plane = Plane;
  3981. var Viewport = (function () {
  3982. /**
  3983. * Creates a Viewport object located at (x, y) and sized (width, height).
  3984. */
  3985. function Viewport(x, y, width, height) {
  3986. this.x = x;
  3987. this.y = y;
  3988. this.width = width;
  3989. this.height = height;
  3990. }
  3991. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  3992. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  3993. };
  3994. /**
  3995. * Returns a new Viewport copied from the current one.
  3996. */
  3997. Viewport.prototype.clone = function () {
  3998. return new Viewport(this.x, this.y, this.width, this.height);
  3999. };
  4000. return Viewport;
  4001. }());
  4002. BABYLON.Viewport = Viewport;
  4003. var Frustum = (function () {
  4004. function Frustum() {
  4005. }
  4006. /**
  4007. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4008. */
  4009. Frustum.GetPlanes = function (transform) {
  4010. var frustumPlanes = [];
  4011. for (var index = 0; index < 6; index++) {
  4012. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4013. }
  4014. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4015. return frustumPlanes;
  4016. };
  4017. /**
  4018. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4019. */
  4020. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4021. // Near
  4022. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  4023. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  4024. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  4025. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  4026. frustumPlanes[0].normalize();
  4027. // Far
  4028. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  4029. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  4030. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  4031. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  4032. frustumPlanes[1].normalize();
  4033. // Left
  4034. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  4035. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  4036. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  4037. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  4038. frustumPlanes[2].normalize();
  4039. // Right
  4040. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  4041. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  4042. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  4043. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  4044. frustumPlanes[3].normalize();
  4045. // Top
  4046. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  4047. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  4048. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  4049. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  4050. frustumPlanes[4].normalize();
  4051. // Bottom
  4052. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  4053. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  4054. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  4055. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  4056. frustumPlanes[5].normalize();
  4057. };
  4058. return Frustum;
  4059. }());
  4060. BABYLON.Frustum = Frustum;
  4061. var Space;
  4062. (function (Space) {
  4063. Space[Space["LOCAL"] = 0] = "LOCAL";
  4064. Space[Space["WORLD"] = 1] = "WORLD";
  4065. Space[Space["BONE"] = 2] = "BONE";
  4066. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4067. var Axis = (function () {
  4068. function Axis() {
  4069. }
  4070. return Axis;
  4071. }());
  4072. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4073. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4074. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4075. BABYLON.Axis = Axis;
  4076. ;
  4077. var BezierCurve = (function () {
  4078. function BezierCurve() {
  4079. }
  4080. /**
  4081. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4082. */
  4083. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4084. // Extract X (which is equal to time here)
  4085. var f0 = 1 - 3 * x2 + 3 * x1;
  4086. var f1 = 3 * x2 - 6 * x1;
  4087. var f2 = 3 * x1;
  4088. var refinedT = t;
  4089. for (var i = 0; i < 5; i++) {
  4090. var refinedT2 = refinedT * refinedT;
  4091. var refinedT3 = refinedT2 * refinedT;
  4092. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4093. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4094. refinedT -= (x - t) * slope;
  4095. refinedT = Math.min(1, Math.max(0, refinedT));
  4096. }
  4097. // Resolve cubic bezier for the given x
  4098. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4099. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4100. Math.pow(refinedT, 3);
  4101. };
  4102. return BezierCurve;
  4103. }());
  4104. BABYLON.BezierCurve = BezierCurve;
  4105. var Orientation;
  4106. (function (Orientation) {
  4107. Orientation[Orientation["CW"] = 0] = "CW";
  4108. Orientation[Orientation["CCW"] = 1] = "CCW";
  4109. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4110. var Angle = (function () {
  4111. /**
  4112. * Creates an Angle object of "radians" radians (float).
  4113. */
  4114. function Angle(radians) {
  4115. var _this = this;
  4116. /**
  4117. * Returns the Angle value in degrees (float).
  4118. */
  4119. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4120. /**
  4121. * Returns the Angle value in radians (float).
  4122. */
  4123. this.radians = function () { return _this._radians; };
  4124. this._radians = radians;
  4125. if (this._radians < 0.0)
  4126. this._radians += (2.0 * Math.PI);
  4127. }
  4128. /**
  4129. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4130. */
  4131. Angle.BetweenTwoPoints = function (a, b) {
  4132. var delta = b.subtract(a);
  4133. var theta = Math.atan2(delta.y, delta.x);
  4134. return new Angle(theta);
  4135. };
  4136. /**
  4137. * Returns a new Angle object from the passed float in radians.
  4138. */
  4139. Angle.FromRadians = function (radians) {
  4140. return new Angle(radians);
  4141. };
  4142. /**
  4143. * Returns a new Angle object from the passed float in degrees.
  4144. */
  4145. Angle.FromDegrees = function (degrees) {
  4146. return new Angle(degrees * Math.PI / 180.0);
  4147. };
  4148. return Angle;
  4149. }());
  4150. BABYLON.Angle = Angle;
  4151. var Arc2 = (function () {
  4152. /**
  4153. * Creates an Arc object from the three passed points : start, middle and end.
  4154. */
  4155. function Arc2(startPoint, midPoint, endPoint) {
  4156. this.startPoint = startPoint;
  4157. this.midPoint = midPoint;
  4158. this.endPoint = endPoint;
  4159. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4160. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4161. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4162. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4163. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  4164. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4165. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4166. var a1 = this.startAngle.degrees();
  4167. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4168. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4169. // angles correction
  4170. if (a2 - a1 > +180.0)
  4171. a2 -= 360.0;
  4172. if (a2 - a1 < -180.0)
  4173. a2 += 360.0;
  4174. if (a3 - a2 > +180.0)
  4175. a3 -= 360.0;
  4176. if (a3 - a2 < -180.0)
  4177. a3 += 360.0;
  4178. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4179. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4180. }
  4181. return Arc2;
  4182. }());
  4183. BABYLON.Arc2 = Arc2;
  4184. var Path2 = (function () {
  4185. /**
  4186. * Creates a Path2 object from the starting 2D coordinates x and y.
  4187. */
  4188. function Path2(x, y) {
  4189. this._points = new Array();
  4190. this._length = 0.0;
  4191. this.closed = false;
  4192. this._points.push(new Vector2(x, y));
  4193. }
  4194. /**
  4195. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4196. * Returns the updated Path2.
  4197. */
  4198. Path2.prototype.addLineTo = function (x, y) {
  4199. if (closed) {
  4200. //Tools.Error("cannot add lines to closed paths");
  4201. return this;
  4202. }
  4203. var newPoint = new Vector2(x, y);
  4204. var previousPoint = this._points[this._points.length - 1];
  4205. this._points.push(newPoint);
  4206. this._length += newPoint.subtract(previousPoint).length();
  4207. return this;
  4208. };
  4209. /**
  4210. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  4211. * Returns the updated Path2.
  4212. */
  4213. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4214. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4215. if (closed) {
  4216. //Tools.Error("cannot add arcs to closed paths");
  4217. return this;
  4218. }
  4219. var startPoint = this._points[this._points.length - 1];
  4220. var midPoint = new Vector2(midX, midY);
  4221. var endPoint = new Vector2(endX, endY);
  4222. var arc = new Arc2(startPoint, midPoint, endPoint);
  4223. var increment = arc.angle.radians() / numberOfSegments;
  4224. if (arc.orientation === Orientation.CW)
  4225. increment *= -1;
  4226. var currentAngle = arc.startAngle.radians() + increment;
  4227. for (var i = 0; i < numberOfSegments; i++) {
  4228. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4229. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4230. this.addLineTo(x, y);
  4231. currentAngle += increment;
  4232. }
  4233. return this;
  4234. };
  4235. /**
  4236. * Closes the Path2.
  4237. * Returns the Path2.
  4238. */
  4239. Path2.prototype.close = function () {
  4240. this.closed = true;
  4241. return this;
  4242. };
  4243. /**
  4244. * Returns the Path2 total length (float).
  4245. */
  4246. Path2.prototype.length = function () {
  4247. var result = this._length;
  4248. if (!this.closed) {
  4249. var lastPoint = this._points[this._points.length - 1];
  4250. var firstPoint = this._points[0];
  4251. result += (firstPoint.subtract(lastPoint).length());
  4252. }
  4253. return result;
  4254. };
  4255. /**
  4256. * Returns the Path2 internal array of points.
  4257. */
  4258. Path2.prototype.getPoints = function () {
  4259. return this._points;
  4260. };
  4261. /**
  4262. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4263. */
  4264. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4265. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4266. //Tools.Error("normalized length position should be between 0 and 1.");
  4267. return Vector2.Zero();
  4268. }
  4269. var lengthPosition = normalizedLengthPosition * this.length();
  4270. var previousOffset = 0;
  4271. for (var i = 0; i < this._points.length; i++) {
  4272. var j = (i + 1) % this._points.length;
  4273. var a = this._points[i];
  4274. var b = this._points[j];
  4275. var bToA = b.subtract(a);
  4276. var nextOffset = (bToA.length() + previousOffset);
  4277. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4278. var dir = bToA.normalize();
  4279. var localOffset = lengthPosition - previousOffset;
  4280. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4281. }
  4282. previousOffset = nextOffset;
  4283. }
  4284. //Tools.Error("internal error");
  4285. return Vector2.Zero();
  4286. };
  4287. /**
  4288. * Returns a new Path2 starting at the coordinates (x, y).
  4289. */
  4290. Path2.StartingAt = function (x, y) {
  4291. return new Path2(x, y);
  4292. };
  4293. return Path2;
  4294. }());
  4295. BABYLON.Path2 = Path2;
  4296. var Path3D = (function () {
  4297. /**
  4298. * new Path3D(path, normal, raw)
  4299. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4300. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4301. * path : an array of Vector3, the curve axis of the Path3D
  4302. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4303. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4304. */
  4305. function Path3D(path, firstNormal, raw) {
  4306. this.path = path;
  4307. this._curve = new Array();
  4308. this._distances = new Array();
  4309. this._tangents = new Array();
  4310. this._normals = new Array();
  4311. this._binormals = new Array();
  4312. for (var p = 0; p < path.length; p++) {
  4313. this._curve[p] = path[p].clone(); // hard copy
  4314. }
  4315. this._raw = raw || false;
  4316. this._compute(firstNormal);
  4317. }
  4318. /**
  4319. * Returns the Path3D array of successive Vector3 designing its curve.
  4320. */
  4321. Path3D.prototype.getCurve = function () {
  4322. return this._curve;
  4323. };
  4324. /**
  4325. * Returns an array populated with tangent vectors on each Path3D curve point.
  4326. */
  4327. Path3D.prototype.getTangents = function () {
  4328. return this._tangents;
  4329. };
  4330. /**
  4331. * Returns an array populated with normal vectors on each Path3D curve point.
  4332. */
  4333. Path3D.prototype.getNormals = function () {
  4334. return this._normals;
  4335. };
  4336. /**
  4337. * Returns an array populated with binormal vectors on each Path3D curve point.
  4338. */
  4339. Path3D.prototype.getBinormals = function () {
  4340. return this._binormals;
  4341. };
  4342. /**
  4343. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4344. */
  4345. Path3D.prototype.getDistances = function () {
  4346. return this._distances;
  4347. };
  4348. /**
  4349. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4350. * Returns the same object updated.
  4351. */
  4352. Path3D.prototype.update = function (path, firstNormal) {
  4353. for (var p = 0; p < path.length; p++) {
  4354. this._curve[p].x = path[p].x;
  4355. this._curve[p].y = path[p].y;
  4356. this._curve[p].z = path[p].z;
  4357. }
  4358. this._compute(firstNormal);
  4359. return this;
  4360. };
  4361. // private function compute() : computes tangents, normals and binormals
  4362. Path3D.prototype._compute = function (firstNormal) {
  4363. var l = this._curve.length;
  4364. // first and last tangents
  4365. this._tangents[0] = this._getFirstNonNullVector(0);
  4366. if (!this._raw) {
  4367. this._tangents[0].normalize();
  4368. }
  4369. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4370. if (!this._raw) {
  4371. this._tangents[l - 1].normalize();
  4372. }
  4373. // normals and binormals at first point : arbitrary vector with _normalVector()
  4374. var tg0 = this._tangents[0];
  4375. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4376. this._normals[0] = pp0;
  4377. if (!this._raw) {
  4378. this._normals[0].normalize();
  4379. }
  4380. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4381. if (!this._raw) {
  4382. this._binormals[0].normalize();
  4383. }
  4384. this._distances[0] = 0.0;
  4385. // normals and binormals : next points
  4386. var prev; // previous vector (segment)
  4387. var cur; // current vector (segment)
  4388. var curTang; // current tangent
  4389. // previous normal
  4390. var prevBinor; // previous binormal
  4391. for (var i = 1; i < l; i++) {
  4392. // tangents
  4393. prev = this._getLastNonNullVector(i);
  4394. if (i < l - 1) {
  4395. cur = this._getFirstNonNullVector(i);
  4396. this._tangents[i] = prev.add(cur);
  4397. this._tangents[i].normalize();
  4398. }
  4399. this._distances[i] = this._distances[i - 1] + prev.length();
  4400. // normals and binormals
  4401. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4402. curTang = this._tangents[i];
  4403. prevBinor = this._binormals[i - 1];
  4404. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4405. if (!this._raw) {
  4406. this._normals[i].normalize();
  4407. }
  4408. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4409. if (!this._raw) {
  4410. this._binormals[i].normalize();
  4411. }
  4412. }
  4413. };
  4414. // private function getFirstNonNullVector(index)
  4415. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4416. Path3D.prototype._getFirstNonNullVector = function (index) {
  4417. var i = 1;
  4418. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4419. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4420. i++;
  4421. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4422. }
  4423. return nNVector;
  4424. };
  4425. // private function getLastNonNullVector(index)
  4426. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4427. Path3D.prototype._getLastNonNullVector = function (index) {
  4428. var i = 1;
  4429. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4430. while (nLVector.length() === 0 && index > i + 1) {
  4431. i++;
  4432. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4433. }
  4434. return nLVector;
  4435. };
  4436. // private function normalVector(v0, vt, va) :
  4437. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4438. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4439. Path3D.prototype._normalVector = function (v0, vt, va) {
  4440. var normal0;
  4441. var tgl = vt.length();
  4442. if (tgl === 0.0) {
  4443. tgl = 1.0;
  4444. }
  4445. if (va === undefined || va === null) {
  4446. var point;
  4447. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4448. point = new Vector3(0.0, -1.0, 0.0);
  4449. }
  4450. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4451. point = new Vector3(1.0, 0.0, 0.0);
  4452. }
  4453. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4454. point = new Vector3(0.0, 0.0, 1.0);
  4455. }
  4456. normal0 = Vector3.Cross(vt, point);
  4457. }
  4458. else {
  4459. normal0 = Vector3.Cross(vt, va);
  4460. Vector3.CrossToRef(normal0, vt, normal0);
  4461. }
  4462. normal0.normalize();
  4463. return normal0;
  4464. };
  4465. return Path3D;
  4466. }());
  4467. BABYLON.Path3D = Path3D;
  4468. var Curve3 = (function () {
  4469. /**
  4470. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4471. * A Curve3 is designed from a series of successive Vector3.
  4472. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4473. */
  4474. function Curve3(points) {
  4475. this._length = 0.0;
  4476. this._points = points;
  4477. this._length = this._computeLength(points);
  4478. }
  4479. /**
  4480. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4481. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4482. * @param v1 (Vector3) the control point
  4483. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4484. * @param nbPoints (integer) the wanted number of points in the curve
  4485. */
  4486. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4487. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4488. var bez = new Array();
  4489. var equation = function (t, val0, val1, val2) {
  4490. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4491. return res;
  4492. };
  4493. for (var i = 0; i <= nbPoints; i++) {
  4494. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  4495. }
  4496. return new Curve3(bez);
  4497. };
  4498. /**
  4499. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4500. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4501. * @param v1 (Vector3) the first control point
  4502. * @param v2 (Vector3) the second control point
  4503. * @param v3 (Vector3) the end point of the Cubic Bezier
  4504. * @param nbPoints (integer) the wanted number of points in the curve
  4505. */
  4506. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4507. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4508. var bez = new Array();
  4509. var equation = function (t, val0, val1, val2, val3) {
  4510. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  4511. return res;
  4512. };
  4513. for (var i = 0; i <= nbPoints; i++) {
  4514. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  4515. }
  4516. return new Curve3(bez);
  4517. };
  4518. /**
  4519. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4520. * @param p1 (Vector3) the origin point of the Hermite Spline
  4521. * @param t1 (Vector3) the tangent vector at the origin point
  4522. * @param p2 (Vector3) the end point of the Hermite Spline
  4523. * @param t2 (Vector3) the tangent vector at the end point
  4524. * @param nbPoints (integer) the wanted number of points in the curve
  4525. */
  4526. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4527. var hermite = new Array();
  4528. var step = 1.0 / nbPoints;
  4529. for (var i = 0; i <= nbPoints; i++) {
  4530. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4531. }
  4532. return new Curve3(hermite);
  4533. };
  4534. /**
  4535. * Returns a Curve3 object along a CatmullRom Spline curve :
  4536. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4537. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4538. */
  4539. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4540. var totalPoints = new Array();
  4541. totalPoints.push(points[0].clone());
  4542. Array.prototype.push.apply(totalPoints, points);
  4543. totalPoints.push(points[points.length - 1].clone());
  4544. var catmullRom = new Array();
  4545. var step = 1.0 / nbPoints;
  4546. for (var i = 0; i < totalPoints.length - 3; i++) {
  4547. var amount = 0.0;
  4548. for (var c = 0; c < nbPoints; c++) {
  4549. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4550. amount += step;
  4551. }
  4552. }
  4553. i--;
  4554. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4555. return new Curve3(catmullRom);
  4556. };
  4557. /**
  4558. * Returns the Curve3 stored array of successive Vector3
  4559. */
  4560. Curve3.prototype.getPoints = function () {
  4561. return this._points;
  4562. };
  4563. /**
  4564. * Returns the computed length (float) of the curve.
  4565. */
  4566. Curve3.prototype.length = function () {
  4567. return this._length;
  4568. };
  4569. /**
  4570. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4571. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4572. * curveA and curveB keep unchanged.
  4573. */
  4574. Curve3.prototype.continue = function (curve) {
  4575. var lastPoint = this._points[this._points.length - 1];
  4576. var continuedPoints = this._points.slice();
  4577. var curvePoints = curve.getPoints();
  4578. for (var i = 1; i < curvePoints.length; i++) {
  4579. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4580. }
  4581. var continuedCurve = new Curve3(continuedPoints);
  4582. return continuedCurve;
  4583. };
  4584. Curve3.prototype._computeLength = function (path) {
  4585. var l = 0;
  4586. for (var i = 1; i < path.length; i++) {
  4587. l += (path[i].subtract(path[i - 1])).length();
  4588. }
  4589. return l;
  4590. };
  4591. return Curve3;
  4592. }());
  4593. BABYLON.Curve3 = Curve3;
  4594. // SphericalHarmonics
  4595. var SphericalHarmonics = (function () {
  4596. function SphericalHarmonics() {
  4597. this.L00 = Vector3.Zero();
  4598. this.L1_1 = Vector3.Zero();
  4599. this.L10 = Vector3.Zero();
  4600. this.L11 = Vector3.Zero();
  4601. this.L2_2 = Vector3.Zero();
  4602. this.L2_1 = Vector3.Zero();
  4603. this.L20 = Vector3.Zero();
  4604. this.L21 = Vector3.Zero();
  4605. this.L22 = Vector3.Zero();
  4606. }
  4607. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  4608. var colorVector = new Vector3(color.r, color.g, color.b);
  4609. var c = colorVector.scale(deltaSolidAngle);
  4610. this.L00 = this.L00.add(c.scale(0.282095));
  4611. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  4612. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  4613. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  4614. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  4615. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  4616. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  4617. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  4618. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  4619. };
  4620. SphericalHarmonics.prototype.scale = function (scale) {
  4621. this.L00 = this.L00.scale(scale);
  4622. this.L1_1 = this.L1_1.scale(scale);
  4623. this.L10 = this.L10.scale(scale);
  4624. this.L11 = this.L11.scale(scale);
  4625. this.L2_2 = this.L2_2.scale(scale);
  4626. this.L2_1 = this.L2_1.scale(scale);
  4627. this.L20 = this.L20.scale(scale);
  4628. this.L21 = this.L21.scale(scale);
  4629. this.L22 = this.L22.scale(scale);
  4630. };
  4631. return SphericalHarmonics;
  4632. }());
  4633. BABYLON.SphericalHarmonics = SphericalHarmonics;
  4634. // SphericalPolynomial
  4635. var SphericalPolynomial = (function () {
  4636. function SphericalPolynomial() {
  4637. this.x = Vector3.Zero();
  4638. this.y = Vector3.Zero();
  4639. this.z = Vector3.Zero();
  4640. this.xx = Vector3.Zero();
  4641. this.yy = Vector3.Zero();
  4642. this.zz = Vector3.Zero();
  4643. this.xy = Vector3.Zero();
  4644. this.yz = Vector3.Zero();
  4645. this.zx = Vector3.Zero();
  4646. }
  4647. SphericalPolynomial.prototype.addAmbient = function (color) {
  4648. var colorVector = new Vector3(color.r, color.g, color.b);
  4649. this.xx = this.xx.add(colorVector);
  4650. this.yy = this.yy.add(colorVector);
  4651. this.zz = this.zz.add(colorVector);
  4652. };
  4653. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  4654. var result = new SphericalPolynomial();
  4655. result.x = harmonics.L11.scale(1.02333);
  4656. result.y = harmonics.L1_1.scale(1.02333);
  4657. result.z = harmonics.L10.scale(1.02333);
  4658. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  4659. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  4660. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  4661. result.yz = harmonics.L2_1.scale(0.858086);
  4662. result.zx = harmonics.L21.scale(0.858086);
  4663. result.xy = harmonics.L2_2.scale(0.858086);
  4664. return result;
  4665. };
  4666. return SphericalPolynomial;
  4667. }());
  4668. BABYLON.SphericalPolynomial = SphericalPolynomial;
  4669. // Vertex formats
  4670. var PositionNormalVertex = (function () {
  4671. function PositionNormalVertex(position, normal) {
  4672. if (position === void 0) { position = Vector3.Zero(); }
  4673. if (normal === void 0) { normal = Vector3.Up(); }
  4674. this.position = position;
  4675. this.normal = normal;
  4676. }
  4677. PositionNormalVertex.prototype.clone = function () {
  4678. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4679. };
  4680. return PositionNormalVertex;
  4681. }());
  4682. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4683. var PositionNormalTextureVertex = (function () {
  4684. function PositionNormalTextureVertex(position, normal, uv) {
  4685. if (position === void 0) { position = Vector3.Zero(); }
  4686. if (normal === void 0) { normal = Vector3.Up(); }
  4687. if (uv === void 0) { uv = Vector2.Zero(); }
  4688. this.position = position;
  4689. this.normal = normal;
  4690. this.uv = uv;
  4691. }
  4692. PositionNormalTextureVertex.prototype.clone = function () {
  4693. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4694. };
  4695. return PositionNormalTextureVertex;
  4696. }());
  4697. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4698. // Temporary pre-allocated objects for engine internal use
  4699. // usage in any internal function :
  4700. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4701. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4702. var Tmp = (function () {
  4703. function Tmp() {
  4704. }
  4705. return Tmp;
  4706. }());
  4707. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4708. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4709. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4710. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4711. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4712. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4713. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4714. Matrix.Zero(), Matrix.Zero(),
  4715. Matrix.Zero(), Matrix.Zero(),
  4716. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4717. BABYLON.Tmp = Tmp;
  4718. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4719. var MathTmp = (function () {
  4720. function MathTmp() {
  4721. }
  4722. return MathTmp;
  4723. }());
  4724. MathTmp.Vector3 = [Vector3.Zero()];
  4725. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4726. MathTmp.Quaternion = [Quaternion.Zero()];
  4727. })(BABYLON || (BABYLON = {}));
  4728. //# sourceMappingURL=babylon.math.js.map
  4729. //# sourceMappingURL=babylon.mixins.js.map
  4730. var BABYLON;
  4731. (function (BABYLON) {
  4732. function generateSerializableMember(type, sourceName) {
  4733. return function (target, propertyKey) {
  4734. if (!target.__serializableMembers) {
  4735. target.__serializableMembers = {};
  4736. }
  4737. if (!target.__serializableMembers[propertyKey]) {
  4738. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  4739. }
  4740. };
  4741. }
  4742. function generateExpandMember(setCallback, targetKey) {
  4743. return function (target, propertyKey) {
  4744. var key = targetKey || ("_" + propertyKey);
  4745. Object.defineProperty(target, propertyKey, {
  4746. get: function () {
  4747. return this[key];
  4748. },
  4749. set: function (value) {
  4750. if (this[key] === value) {
  4751. return;
  4752. }
  4753. this[key] = value;
  4754. if (setCallback) {
  4755. target[setCallback].apply(this);
  4756. }
  4757. },
  4758. enumerable: true,
  4759. configurable: true
  4760. });
  4761. };
  4762. }
  4763. function expandToProperty(callback, targetKey) {
  4764. return generateExpandMember(callback, targetKey);
  4765. }
  4766. BABYLON.expandToProperty = expandToProperty;
  4767. function serialize(sourceName) {
  4768. return generateSerializableMember(0, sourceName); // value member
  4769. }
  4770. BABYLON.serialize = serialize;
  4771. function serializeAsTexture(sourceName) {
  4772. return generateSerializableMember(1, sourceName); // texture member
  4773. }
  4774. BABYLON.serializeAsTexture = serializeAsTexture;
  4775. function serializeAsColor3(sourceName) {
  4776. return generateSerializableMember(2, sourceName); // color3 member
  4777. }
  4778. BABYLON.serializeAsColor3 = serializeAsColor3;
  4779. function serializeAsFresnelParameters(sourceName) {
  4780. return generateSerializableMember(3, sourceName); // fresnel parameters member
  4781. }
  4782. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  4783. function serializeAsVector2(sourceName) {
  4784. return generateSerializableMember(4, sourceName); // vector2 member
  4785. }
  4786. BABYLON.serializeAsVector2 = serializeAsVector2;
  4787. function serializeAsVector3(sourceName) {
  4788. return generateSerializableMember(5, sourceName); // vector3 member
  4789. }
  4790. BABYLON.serializeAsVector3 = serializeAsVector3;
  4791. function serializeAsMeshReference(sourceName) {
  4792. return generateSerializableMember(6, sourceName); // mesh reference member
  4793. }
  4794. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  4795. function serializeAsColorCurves(sourceName) {
  4796. return generateSerializableMember(7, sourceName); // color curves
  4797. }
  4798. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  4799. var SerializationHelper = (function () {
  4800. function SerializationHelper() {
  4801. }
  4802. SerializationHelper.Serialize = function (entity, serializationObject) {
  4803. if (!serializationObject) {
  4804. serializationObject = {};
  4805. }
  4806. // Tags
  4807. if (BABYLON.Tags) {
  4808. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  4809. }
  4810. // Properties
  4811. for (var property in entity.__serializableMembers) {
  4812. var propertyDescriptor = entity.__serializableMembers[property];
  4813. var targetPropertyName = propertyDescriptor.sourceName || property;
  4814. var propertyType = propertyDescriptor.type;
  4815. var sourceProperty = entity[property];
  4816. if (sourceProperty !== undefined && sourceProperty !== null) {
  4817. switch (propertyType) {
  4818. case 0:
  4819. serializationObject[targetPropertyName] = sourceProperty;
  4820. break;
  4821. case 1:
  4822. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4823. break;
  4824. case 2:
  4825. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4826. break;
  4827. case 3:
  4828. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4829. break;
  4830. case 4:
  4831. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4832. break;
  4833. case 5:
  4834. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4835. break;
  4836. case 6:
  4837. serializationObject[targetPropertyName] = sourceProperty.id;
  4838. break;
  4839. case 7:
  4840. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4841. break;
  4842. }
  4843. }
  4844. }
  4845. return serializationObject;
  4846. };
  4847. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  4848. var destination = creationFunction();
  4849. // Tags
  4850. if (BABYLON.Tags) {
  4851. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4852. }
  4853. // Properties
  4854. for (var property in destination.__serializableMembers) {
  4855. var propertyDescriptor = destination.__serializableMembers[property];
  4856. var sourceProperty = source[propertyDescriptor.sourceName || property];
  4857. var propertyType = propertyDescriptor.type;
  4858. if (sourceProperty !== undefined && sourceProperty !== null) {
  4859. switch (propertyType) {
  4860. case 0:
  4861. destination[property] = sourceProperty;
  4862. break;
  4863. case 1:
  4864. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  4865. break;
  4866. case 2:
  4867. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  4868. break;
  4869. case 3:
  4870. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  4871. break;
  4872. case 4:
  4873. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  4874. break;
  4875. case 5:
  4876. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  4877. break;
  4878. case 6:
  4879. destination[property] = scene.getLastMeshByID(sourceProperty);
  4880. break;
  4881. case 7:
  4882. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  4883. break;
  4884. }
  4885. }
  4886. }
  4887. return destination;
  4888. };
  4889. SerializationHelper.Clone = function (creationFunction, source) {
  4890. var destination = creationFunction();
  4891. // Tags
  4892. if (BABYLON.Tags) {
  4893. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4894. }
  4895. // Properties
  4896. for (var property in destination.__serializableMembers) {
  4897. var propertyDescriptor = destination.__serializableMembers[property];
  4898. var sourceProperty = source[property];
  4899. var propertyType = propertyDescriptor.type;
  4900. if (sourceProperty !== undefined && sourceProperty !== null) {
  4901. switch (propertyType) {
  4902. case 0: // Value
  4903. case 6:
  4904. destination[property] = sourceProperty;
  4905. break;
  4906. case 1: // Texture
  4907. case 2: // Color3
  4908. case 3: // FresnelParameters
  4909. case 4: // Vector2
  4910. case 5: // Vector3
  4911. case 7:
  4912. destination[property] = sourceProperty.clone();
  4913. break;
  4914. }
  4915. }
  4916. }
  4917. return destination;
  4918. };
  4919. return SerializationHelper;
  4920. }());
  4921. BABYLON.SerializationHelper = SerializationHelper;
  4922. })(BABYLON || (BABYLON = {}));
  4923. //# sourceMappingURL=babylon.decorators.js.map
  4924. var BABYLON;
  4925. (function (BABYLON) {
  4926. /**
  4927. * A class serves as a medium between the observable and its observers
  4928. */
  4929. var EventState = (function () {
  4930. /**
  4931. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  4932. */
  4933. function EventState(mask, skipNextObservers) {
  4934. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4935. this.initalize(mask, skipNextObservers);
  4936. }
  4937. EventState.prototype.initalize = function (mask, skipNextObservers) {
  4938. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4939. this.mask = mask;
  4940. this.skipNextObservers = skipNextObservers;
  4941. return this;
  4942. };
  4943. return EventState;
  4944. }());
  4945. BABYLON.EventState = EventState;
  4946. /**
  4947. * Represent an Observer registered to a given Observable object.
  4948. */
  4949. var Observer = (function () {
  4950. function Observer(callback, mask) {
  4951. this.callback = callback;
  4952. this.mask = mask;
  4953. }
  4954. return Observer;
  4955. }());
  4956. BABYLON.Observer = Observer;
  4957. /**
  4958. * The Observable class is a simple implementation of the Observable pattern.
  4959. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  4960. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  4961. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  4962. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  4963. */
  4964. var Observable = (function () {
  4965. function Observable() {
  4966. this._observers = new Array();
  4967. this._eventState = new EventState(0);
  4968. }
  4969. /**
  4970. * Create a new Observer with the specified callback
  4971. * @param callback the callback that will be executed for that Observer
  4972. * @param mask the mask used to filter observers
  4973. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  4974. */
  4975. Observable.prototype.add = function (callback, mask, insertFirst) {
  4976. if (mask === void 0) { mask = -1; }
  4977. if (insertFirst === void 0) { insertFirst = false; }
  4978. if (!callback) {
  4979. return null;
  4980. }
  4981. var observer = new Observer(callback, mask);
  4982. if (insertFirst) {
  4983. this._observers.unshift(observer);
  4984. }
  4985. else {
  4986. this._observers.push(observer);
  4987. }
  4988. return observer;
  4989. };
  4990. /**
  4991. * Remove an Observer from the Observable object
  4992. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  4993. */
  4994. Observable.prototype.remove = function (observer) {
  4995. var index = this._observers.indexOf(observer);
  4996. if (index !== -1) {
  4997. this._observers.splice(index, 1);
  4998. return true;
  4999. }
  5000. return false;
  5001. };
  5002. /**
  5003. * Remove a callback from the Observable object
  5004. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5005. */
  5006. Observable.prototype.removeCallback = function (callback) {
  5007. for (var index = 0; index < this._observers.length; index++) {
  5008. if (this._observers[index].callback === callback) {
  5009. this._observers.splice(index, 1);
  5010. return true;
  5011. }
  5012. }
  5013. return false;
  5014. };
  5015. /**
  5016. * Notify all Observers by calling their respective callback with the given data
  5017. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5018. * @param eventData
  5019. * @param mask
  5020. */
  5021. Observable.prototype.notifyObservers = function (eventData, mask) {
  5022. if (mask === void 0) { mask = -1; }
  5023. var state = this._eventState;
  5024. state.mask = mask;
  5025. state.skipNextObservers = false;
  5026. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5027. var obs = _a[_i];
  5028. if (obs.mask & mask) {
  5029. obs.callback(eventData, state);
  5030. }
  5031. if (state.skipNextObservers) {
  5032. return false;
  5033. }
  5034. }
  5035. return true;
  5036. };
  5037. /**
  5038. * return true is the Observable has at least one Observer registered
  5039. */
  5040. Observable.prototype.hasObservers = function () {
  5041. return this._observers.length > 0;
  5042. };
  5043. /**
  5044. * Clear the list of observers
  5045. */
  5046. Observable.prototype.clear = function () {
  5047. this._observers = new Array();
  5048. };
  5049. /**
  5050. * Clone the current observable
  5051. */
  5052. Observable.prototype.clone = function () {
  5053. var result = new Observable();
  5054. result._observers = this._observers.slice(0);
  5055. return result;
  5056. };
  5057. /**
  5058. * Does this observable handles observer registered with a given mask
  5059. * @param {number} trigger - the mask to be tested
  5060. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5061. **/
  5062. Observable.prototype.hasSpecificMask = function (mask) {
  5063. if (mask === void 0) { mask = -1; }
  5064. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5065. var obs = _a[_i];
  5066. if (obs.mask & mask && obs.mask === mask) {
  5067. return true;
  5068. }
  5069. }
  5070. return false;
  5071. };
  5072. return Observable;
  5073. }());
  5074. BABYLON.Observable = Observable;
  5075. })(BABYLON || (BABYLON = {}));
  5076. //# sourceMappingURL=babylon.observable.js.map
  5077. var BABYLON;
  5078. (function (BABYLON) {
  5079. var SmartArray = (function () {
  5080. function SmartArray(capacity) {
  5081. this.length = 0;
  5082. this._duplicateId = 0;
  5083. this.data = new Array(capacity);
  5084. this._id = SmartArray._GlobalId++;
  5085. }
  5086. SmartArray.prototype.push = function (value) {
  5087. this.data[this.length++] = value;
  5088. if (this.length > this.data.length) {
  5089. this.data.length *= 2;
  5090. }
  5091. if (!value.__smartArrayFlags) {
  5092. value.__smartArrayFlags = {};
  5093. }
  5094. value.__smartArrayFlags[this._id] = this._duplicateId;
  5095. };
  5096. SmartArray.prototype.forEach = function (func) {
  5097. for (var index = 0; index < this.length; index++) {
  5098. func(this.data[index]);
  5099. }
  5100. };
  5101. SmartArray.prototype.pushNoDuplicate = function (value) {
  5102. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5103. return false;
  5104. }
  5105. this.push(value);
  5106. return true;
  5107. };
  5108. SmartArray.prototype.sort = function (compareFn) {
  5109. this.data.sort(compareFn);
  5110. };
  5111. SmartArray.prototype.reset = function () {
  5112. this.length = 0;
  5113. this._duplicateId++;
  5114. };
  5115. SmartArray.prototype.dispose = function () {
  5116. this.reset();
  5117. this.data.length = 0;
  5118. };
  5119. SmartArray.prototype.concat = function (array) {
  5120. if (array.length === 0) {
  5121. return;
  5122. }
  5123. if (this.length + array.length > this.data.length) {
  5124. this.data.length = (this.length + array.length) * 2;
  5125. }
  5126. for (var index = 0; index < array.length; index++) {
  5127. this.data[this.length++] = (array.data || array)[index];
  5128. }
  5129. };
  5130. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5131. if (array.length === 0) {
  5132. return;
  5133. }
  5134. if (this.length + array.length > this.data.length) {
  5135. this.data.length = (this.length + array.length) * 2;
  5136. }
  5137. for (var index = 0; index < array.length; index++) {
  5138. var item = (array.data || array)[index];
  5139. this.pushNoDuplicate(item);
  5140. }
  5141. };
  5142. SmartArray.prototype.indexOf = function (value) {
  5143. var position = this.data.indexOf(value);
  5144. if (position >= this.length) {
  5145. return -1;
  5146. }
  5147. return position;
  5148. };
  5149. SmartArray.prototype.contains = function (value) {
  5150. return this.data.indexOf(value) !== -1;
  5151. };
  5152. return SmartArray;
  5153. }());
  5154. // Statics
  5155. SmartArray._GlobalId = 0;
  5156. BABYLON.SmartArray = SmartArray;
  5157. })(BABYLON || (BABYLON = {}));
  5158. //# sourceMappingURL=babylon.smartArray.js.map
  5159. var BABYLON;
  5160. (function (BABYLON) {
  5161. // Screenshots
  5162. var screenshotCanvas;
  5163. var cloneValue = function (source, destinationObject) {
  5164. if (!source)
  5165. return null;
  5166. if (source instanceof BABYLON.Mesh) {
  5167. return null;
  5168. }
  5169. if (source instanceof BABYLON.SubMesh) {
  5170. return source.clone(destinationObject);
  5171. }
  5172. else if (source.clone) {
  5173. return source.clone();
  5174. }
  5175. return null;
  5176. };
  5177. var Tools = (function () {
  5178. function Tools() {
  5179. }
  5180. ;
  5181. /**
  5182. * Interpolates between a and b via alpha
  5183. * @param a The lower value (returned when alpha = 0)
  5184. * @param b The upper value (returned when alpha = 1)
  5185. * @param alpha The interpolation-factor
  5186. * @return The mixed value
  5187. */
  5188. Tools.Mix = function (a, b, alpha) {
  5189. return a * (1 - alpha) + b * alpha;
  5190. };
  5191. Tools.Instantiate = function (className) {
  5192. var arr = className.split(".");
  5193. var fn = (window || this);
  5194. for (var i = 0, len = arr.length; i < len; i++) {
  5195. fn = fn[arr[i]];
  5196. }
  5197. if (typeof fn !== "function") {
  5198. return null;
  5199. }
  5200. return fn;
  5201. };
  5202. Tools.SetImmediate = function (action) {
  5203. if (window.setImmediate) {
  5204. window.setImmediate(action);
  5205. }
  5206. else {
  5207. setTimeout(action, 1);
  5208. }
  5209. };
  5210. Tools.IsExponentOfTwo = function (value) {
  5211. var count = 1;
  5212. do {
  5213. count *= 2;
  5214. } while (count < value);
  5215. return count === value;
  5216. };
  5217. /**
  5218. * Find the next highest power of two.
  5219. * @param x Number to start search from.
  5220. * @return Next highest power of two.
  5221. */
  5222. Tools.CeilingPOT = function (x) {
  5223. x--;
  5224. x |= x >> 1;
  5225. x |= x >> 2;
  5226. x |= x >> 4;
  5227. x |= x >> 8;
  5228. x |= x >> 16;
  5229. x++;
  5230. return x;
  5231. };
  5232. /**
  5233. * Find the next lowest power of two.
  5234. * @param x Number to start search from.
  5235. * @return Next lowest power of two.
  5236. */
  5237. Tools.FloorPOT = function (x) {
  5238. x = x | (x >> 1);
  5239. x = x | (x >> 2);
  5240. x = x | (x >> 4);
  5241. x = x | (x >> 8);
  5242. x = x | (x >> 16);
  5243. return x - (x >> 1);
  5244. };
  5245. /**
  5246. * Find the nearest power of two.
  5247. * @param x Number to start search from.
  5248. * @return Next nearest power of two.
  5249. */
  5250. Tools.NearestPOT = function (x) {
  5251. var c = Tools.CeilingPOT(x);
  5252. var f = Tools.FloorPOT(x);
  5253. return (c - x) > (x - f) ? f : c;
  5254. };
  5255. Tools.GetExponentOfTwo = function (value, max, mode) {
  5256. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5257. var pot;
  5258. switch (mode) {
  5259. case BABYLON.Engine.SCALEMODE_FLOOR:
  5260. pot = Tools.FloorPOT(value);
  5261. break;
  5262. case BABYLON.Engine.SCALEMODE_NEAREST:
  5263. pot = Tools.NearestPOT(value);
  5264. break;
  5265. case BABYLON.Engine.SCALEMODE_CEILING:
  5266. pot = Tools.CeilingPOT(value);
  5267. break;
  5268. }
  5269. return Math.min(pot, max);
  5270. };
  5271. Tools.GetFilename = function (path) {
  5272. var index = path.lastIndexOf("/");
  5273. if (index < 0)
  5274. return path;
  5275. return path.substring(index + 1);
  5276. };
  5277. Tools.GetDOMTextContent = function (element) {
  5278. var result = "";
  5279. var child = element.firstChild;
  5280. while (child) {
  5281. if (child.nodeType === 3) {
  5282. result += child.textContent;
  5283. }
  5284. child = child.nextSibling;
  5285. }
  5286. return result;
  5287. };
  5288. Tools.ToDegrees = function (angle) {
  5289. return angle * 180 / Math.PI;
  5290. };
  5291. Tools.ToRadians = function (angle) {
  5292. return angle * Math.PI / 180;
  5293. };
  5294. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5295. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5296. var output = "";
  5297. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5298. var i = 0;
  5299. var bytes = new Uint8Array(buffer);
  5300. while (i < bytes.length) {
  5301. chr1 = bytes[i++];
  5302. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5303. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5304. enc1 = chr1 >> 2;
  5305. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5306. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5307. enc4 = chr3 & 63;
  5308. if (isNaN(chr2)) {
  5309. enc3 = enc4 = 64;
  5310. }
  5311. else if (isNaN(chr3)) {
  5312. enc4 = 64;
  5313. }
  5314. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5315. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5316. }
  5317. return "data:image/png;base64," + output;
  5318. };
  5319. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5320. if (bias === void 0) { bias = null; }
  5321. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5322. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5323. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5324. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5325. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5326. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5327. }
  5328. if (bias) {
  5329. minimum.x -= minimum.x * bias.x + bias.y;
  5330. minimum.y -= minimum.y * bias.x + bias.y;
  5331. minimum.z -= minimum.z * bias.x + bias.y;
  5332. maximum.x += maximum.x * bias.x + bias.y;
  5333. maximum.y += maximum.y * bias.x + bias.y;
  5334. maximum.z += maximum.z * bias.x + bias.y;
  5335. }
  5336. return {
  5337. minimum: minimum,
  5338. maximum: maximum
  5339. };
  5340. };
  5341. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5342. if (bias === void 0) { bias = null; }
  5343. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5344. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5345. if (!stride) {
  5346. stride = 3;
  5347. }
  5348. for (var index = start; index < start + count; index++) {
  5349. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5350. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5351. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5352. }
  5353. if (bias) {
  5354. minimum.x -= minimum.x * bias.x + bias.y;
  5355. minimum.y -= minimum.y * bias.x + bias.y;
  5356. minimum.z -= minimum.z * bias.x + bias.y;
  5357. maximum.x += maximum.x * bias.x + bias.y;
  5358. maximum.y += maximum.y * bias.x + bias.y;
  5359. maximum.z += maximum.z * bias.x + bias.y;
  5360. }
  5361. return {
  5362. minimum: minimum,
  5363. maximum: maximum
  5364. };
  5365. };
  5366. Tools.Vector2ArrayFeeder = function (array) {
  5367. return function (index) {
  5368. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5369. var length = isFloatArray ? array.length / 2 : array.length;
  5370. if (index >= length) {
  5371. return null;
  5372. }
  5373. if (isFloatArray) {
  5374. var fa = array;
  5375. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5376. }
  5377. var a = array;
  5378. return a[index];
  5379. };
  5380. };
  5381. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5382. if (bias === void 0) { bias = null; }
  5383. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5384. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5385. var i = 0;
  5386. var cur = feeder(i++);
  5387. while (cur) {
  5388. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5389. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5390. cur = feeder(i++);
  5391. }
  5392. if (bias) {
  5393. minimum.x -= minimum.x * bias.x + bias.y;
  5394. minimum.y -= minimum.y * bias.x + bias.y;
  5395. maximum.x += maximum.x * bias.x + bias.y;
  5396. maximum.y += maximum.y * bias.x + bias.y;
  5397. }
  5398. return {
  5399. minimum: minimum,
  5400. maximum: maximum
  5401. };
  5402. };
  5403. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5404. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5405. return undefined;
  5406. return Array.isArray(obj) ? obj : [obj];
  5407. };
  5408. // Misc.
  5409. Tools.GetPointerPrefix = function () {
  5410. var eventPrefix = "pointer";
  5411. // Check if pointer events are supported
  5412. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5413. eventPrefix = "mouse";
  5414. }
  5415. return eventPrefix;
  5416. };
  5417. /**
  5418. * @param func - the function to be called
  5419. * @param requester - the object that will request the next frame. Falls back to window.
  5420. */
  5421. Tools.QueueNewFrame = function (func, requester) {
  5422. if (requester === void 0) { requester = window; }
  5423. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  5424. /*if(requester.isPresenting) {
  5425. return;
  5426. } else*/ if (requester.requestAnimationFrame)
  5427. requester.requestAnimationFrame(func);
  5428. else if (requester.msRequestAnimationFrame)
  5429. requester.msRequestAnimationFrame(func);
  5430. else if (requester.webkitRequestAnimationFrame)
  5431. requester.webkitRequestAnimationFrame(func);
  5432. else if (requester.mozRequestAnimationFrame)
  5433. requester.mozRequestAnimationFrame(func);
  5434. else if (requester.oRequestAnimationFrame)
  5435. requester.oRequestAnimationFrame(func);
  5436. else {
  5437. window.setTimeout(func, 16);
  5438. }
  5439. };
  5440. Tools.RequestFullscreen = function (element) {
  5441. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5442. if (!requestFunction)
  5443. return;
  5444. requestFunction.call(element);
  5445. };
  5446. Tools.ExitFullscreen = function () {
  5447. if (document.exitFullscreen) {
  5448. document.exitFullscreen();
  5449. }
  5450. else if (document.mozCancelFullScreen) {
  5451. document.mozCancelFullScreen();
  5452. }
  5453. else if (document.webkitCancelFullScreen) {
  5454. document.webkitCancelFullScreen();
  5455. }
  5456. else if (document.msCancelFullScreen) {
  5457. document.msCancelFullScreen();
  5458. }
  5459. };
  5460. Tools.SetCorsBehavior = function (url, img) {
  5461. if (Tools.CorsBehavior) {
  5462. switch (typeof (Tools.CorsBehavior)) {
  5463. case "function":
  5464. var result = Tools.CorsBehavior(url);
  5465. if (result) {
  5466. img.crossOrigin = result;
  5467. }
  5468. break;
  5469. case "string":
  5470. default:
  5471. img.crossOrigin = Tools.CorsBehavior;
  5472. break;
  5473. }
  5474. }
  5475. };
  5476. // External files
  5477. Tools.CleanUrl = function (url) {
  5478. url = url.replace(/#/mg, "%23");
  5479. return url;
  5480. };
  5481. Tools.LoadImage = function (url, onload, onerror, database) {
  5482. if (url instanceof ArrayBuffer) {
  5483. url = Tools.EncodeArrayBufferTobase64(url);
  5484. }
  5485. url = Tools.CleanUrl(url);
  5486. var img = new Image();
  5487. if (url.substr(0, 5) !== "data:") {
  5488. Tools.SetCorsBehavior(url, img);
  5489. }
  5490. img.onload = function () {
  5491. onload(img);
  5492. };
  5493. img.onerror = function (err) {
  5494. Tools.Error("Error while trying to load image: " + url);
  5495. if (Tools.UseFallbackTexture) {
  5496. img.src = Tools.fallbackTexture;
  5497. onload(img);
  5498. }
  5499. else {
  5500. onerror();
  5501. }
  5502. };
  5503. var noIndexedDB = function () {
  5504. img.src = url;
  5505. };
  5506. var loadFromIndexedDB = function () {
  5507. database.loadImageFromDB(url, img);
  5508. };
  5509. //ANY database to do!
  5510. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5511. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5512. }
  5513. else {
  5514. if (url.indexOf("file:") !== 0) {
  5515. noIndexedDB();
  5516. }
  5517. else {
  5518. var textureName = url.substring(5).toLowerCase();
  5519. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5520. try {
  5521. var blobURL;
  5522. try {
  5523. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5524. }
  5525. catch (ex) {
  5526. // Chrome doesn't support oneTimeOnly parameter
  5527. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5528. }
  5529. img.src = blobURL;
  5530. }
  5531. catch (e) {
  5532. img.src = null;
  5533. }
  5534. }
  5535. else {
  5536. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5537. img.src = Tools.fallbackTexture;
  5538. }
  5539. }
  5540. }
  5541. return img;
  5542. };
  5543. //ANY
  5544. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5545. url = Tools.CleanUrl(url);
  5546. var noIndexedDB = function () {
  5547. var request = new XMLHttpRequest();
  5548. var loadUrl = Tools.BaseUrl + url;
  5549. request.open('GET', loadUrl, true);
  5550. if (useArrayBuffer) {
  5551. request.responseType = "arraybuffer";
  5552. }
  5553. request.onprogress = progressCallBack;
  5554. request.onreadystatechange = function () {
  5555. // In case of undefined state in some browsers.
  5556. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  5557. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5558. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5559. callback(!useArrayBuffer ? request.responseText : request.response);
  5560. }
  5561. else {
  5562. if (onError) {
  5563. onError(request);
  5564. }
  5565. else {
  5566. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5567. }
  5568. }
  5569. }
  5570. };
  5571. request.send(null);
  5572. };
  5573. var loadFromIndexedDB = function () {
  5574. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5575. };
  5576. if (url.indexOf("file:") !== -1) {
  5577. var fileName = url.substring(5).toLowerCase();
  5578. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5579. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5580. }
  5581. else {
  5582. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5583. }
  5584. }
  5585. else {
  5586. // Caching all files
  5587. if (database && database.enableSceneOffline) {
  5588. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5589. }
  5590. else {
  5591. noIndexedDB();
  5592. }
  5593. }
  5594. };
  5595. /**
  5596. * Load a script (identified by an url). When the url returns, the
  5597. * content of this file is added into a new script element, attached to the DOM (body element)
  5598. */
  5599. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5600. var head = document.getElementsByTagName('head')[0];
  5601. var script = document.createElement('script');
  5602. script.type = 'text/javascript';
  5603. script.src = scriptUrl;
  5604. var self = this;
  5605. script.onload = function () {
  5606. if (onSuccess) {
  5607. onSuccess();
  5608. }
  5609. };
  5610. script.onerror = function () {
  5611. if (onError) {
  5612. onError();
  5613. }
  5614. };
  5615. head.appendChild(script);
  5616. };
  5617. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5618. var reader = new FileReader();
  5619. reader.onload = function (e) {
  5620. //target doesn't have result from ts 1.3
  5621. callback(e.target['result']);
  5622. };
  5623. reader.onprogress = progressCallback;
  5624. reader.readAsDataURL(fileToLoad);
  5625. };
  5626. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5627. var reader = new FileReader();
  5628. reader.onerror = function (e) {
  5629. Tools.Log("Error while reading file: " + fileToLoad.name);
  5630. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5631. };
  5632. reader.onload = function (e) {
  5633. //target doesn't have result from ts 1.3
  5634. callback(e.target['result']);
  5635. };
  5636. reader.onprogress = progressCallBack;
  5637. if (!useArrayBuffer) {
  5638. // Asynchronous read
  5639. reader.readAsText(fileToLoad);
  5640. }
  5641. else {
  5642. reader.readAsArrayBuffer(fileToLoad);
  5643. }
  5644. };
  5645. //returns a downloadable url to a file content.
  5646. Tools.FileAsURL = function (content) {
  5647. var fileBlob = new Blob([content]);
  5648. var url = window.URL || window.webkitURL;
  5649. var link = url.createObjectURL(fileBlob);
  5650. return link;
  5651. };
  5652. // Misc.
  5653. Tools.Format = function (value, decimals) {
  5654. if (decimals === void 0) { decimals = 2; }
  5655. return value.toFixed(decimals);
  5656. };
  5657. Tools.CheckExtends = function (v, min, max) {
  5658. if (v.x < min.x)
  5659. min.x = v.x;
  5660. if (v.y < min.y)
  5661. min.y = v.y;
  5662. if (v.z < min.z)
  5663. min.z = v.z;
  5664. if (v.x > max.x)
  5665. max.x = v.x;
  5666. if (v.y > max.y)
  5667. max.y = v.y;
  5668. if (v.z > max.z)
  5669. max.z = v.z;
  5670. };
  5671. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5672. for (var prop in source) {
  5673. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5674. continue;
  5675. }
  5676. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5677. continue;
  5678. }
  5679. var sourceValue = source[prop];
  5680. var typeOfSourceValue = typeof sourceValue;
  5681. if (typeOfSourceValue === "function") {
  5682. continue;
  5683. }
  5684. if (typeOfSourceValue === "object") {
  5685. if (sourceValue instanceof Array) {
  5686. destination[prop] = [];
  5687. if (sourceValue.length > 0) {
  5688. if (typeof sourceValue[0] == "object") {
  5689. for (var index = 0; index < sourceValue.length; index++) {
  5690. var clonedValue = cloneValue(sourceValue[index], destination);
  5691. if (destination[prop].indexOf(clonedValue) === -1) {
  5692. destination[prop].push(clonedValue);
  5693. }
  5694. }
  5695. }
  5696. else {
  5697. destination[prop] = sourceValue.slice(0);
  5698. }
  5699. }
  5700. }
  5701. else {
  5702. destination[prop] = cloneValue(sourceValue, destination);
  5703. }
  5704. }
  5705. else {
  5706. destination[prop] = sourceValue;
  5707. }
  5708. }
  5709. };
  5710. Tools.IsEmpty = function (obj) {
  5711. for (var i in obj) {
  5712. return false;
  5713. }
  5714. return true;
  5715. };
  5716. Tools.RegisterTopRootEvents = function (events) {
  5717. for (var index = 0; index < events.length; index++) {
  5718. var event = events[index];
  5719. window.addEventListener(event.name, event.handler, false);
  5720. try {
  5721. if (window.parent) {
  5722. window.parent.addEventListener(event.name, event.handler, false);
  5723. }
  5724. }
  5725. catch (e) {
  5726. // Silently fails...
  5727. }
  5728. }
  5729. };
  5730. Tools.UnregisterTopRootEvents = function (events) {
  5731. for (var index = 0; index < events.length; index++) {
  5732. var event = events[index];
  5733. window.removeEventListener(event.name, event.handler);
  5734. try {
  5735. if (window.parent) {
  5736. window.parent.removeEventListener(event.name, event.handler);
  5737. }
  5738. }
  5739. catch (e) {
  5740. // Silently fails...
  5741. }
  5742. }
  5743. };
  5744. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5745. if (mimeType === void 0) { mimeType = "image/png"; }
  5746. // Read the contents of the framebuffer
  5747. var numberOfChannelsByLine = width * 4;
  5748. var halfHeight = height / 2;
  5749. //Reading datas from WebGL
  5750. var data = engine.readPixels(0, 0, width, height);
  5751. //To flip image on Y axis.
  5752. for (var i = 0; i < halfHeight; i++) {
  5753. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5754. var currentCell = j + i * numberOfChannelsByLine;
  5755. var targetLine = height - i - 1;
  5756. var targetCell = j + targetLine * numberOfChannelsByLine;
  5757. var temp = data[currentCell];
  5758. data[currentCell] = data[targetCell];
  5759. data[targetCell] = temp;
  5760. }
  5761. }
  5762. // Create a 2D canvas to store the result
  5763. if (!screenshotCanvas) {
  5764. screenshotCanvas = document.createElement('canvas');
  5765. }
  5766. screenshotCanvas.width = width;
  5767. screenshotCanvas.height = height;
  5768. var context = screenshotCanvas.getContext('2d');
  5769. // Copy the pixels to a 2D canvas
  5770. var imageData = context.createImageData(width, height);
  5771. var castData = (imageData.data);
  5772. castData.set(data);
  5773. context.putImageData(imageData, 0, 0);
  5774. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5775. };
  5776. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5777. if (mimeType === void 0) { mimeType = "image/png"; }
  5778. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5779. if (successCallback) {
  5780. successCallback(base64Image);
  5781. }
  5782. else {
  5783. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5784. if (("download" in document.createElement("a"))) {
  5785. var a = window.document.createElement("a");
  5786. a.href = base64Image;
  5787. var date = new Date();
  5788. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5789. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5790. window.document.body.appendChild(a);
  5791. a.addEventListener("click", function () {
  5792. a.parentElement.removeChild(a);
  5793. });
  5794. a.click();
  5795. //Or opening a new tab with the image if it is not possible to automatically start download.
  5796. }
  5797. else {
  5798. var newWindow = window.open("");
  5799. var img = newWindow.document.createElement("img");
  5800. img.src = base64Image;
  5801. newWindow.document.body.appendChild(img);
  5802. }
  5803. }
  5804. };
  5805. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5806. if (mimeType === void 0) { mimeType = "image/png"; }
  5807. var width;
  5808. var height;
  5809. // If a precision value is specified
  5810. if (size.precision) {
  5811. width = Math.round(engine.getRenderWidth() * size.precision);
  5812. height = Math.round(width / engine.getAspectRatio(camera));
  5813. }
  5814. else if (size.width && size.height) {
  5815. width = size.width;
  5816. height = size.height;
  5817. }
  5818. else if (size.width && !size.height) {
  5819. width = size.width;
  5820. height = Math.round(width / engine.getAspectRatio(camera));
  5821. }
  5822. else if (size.height && !size.width) {
  5823. height = size.height;
  5824. width = Math.round(height * engine.getAspectRatio(camera));
  5825. }
  5826. else if (!isNaN(size)) {
  5827. height = size;
  5828. width = size;
  5829. }
  5830. else {
  5831. Tools.Error("Invalid 'size' parameter !");
  5832. return;
  5833. }
  5834. if (!screenshotCanvas) {
  5835. screenshotCanvas = document.createElement('canvas');
  5836. }
  5837. screenshotCanvas.width = width;
  5838. screenshotCanvas.height = height;
  5839. var renderContext = screenshotCanvas.getContext("2d");
  5840. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  5841. var newWidth = width;
  5842. var newHeight = newWidth / ratio;
  5843. if (newHeight > height) {
  5844. newHeight = height;
  5845. newWidth = newHeight * ratio;
  5846. }
  5847. var offsetX = Math.max(0, width - newWidth) / 2;
  5848. var offsetY = Math.max(0, height - newHeight) / 2;
  5849. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  5850. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5851. };
  5852. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  5853. if (mimeType === void 0) { mimeType = "image/png"; }
  5854. if (samples === void 0) { samples = 1; }
  5855. var width;
  5856. var height;
  5857. //If a precision value is specified
  5858. if (size.precision) {
  5859. width = Math.round(engine.getRenderWidth() * size.precision);
  5860. height = Math.round(width / engine.getAspectRatio(camera));
  5861. size = { width: width, height: height };
  5862. }
  5863. else if (size.width && size.height) {
  5864. width = size.width;
  5865. height = size.height;
  5866. }
  5867. else if (size.width && !size.height) {
  5868. width = size.width;
  5869. height = Math.round(width / engine.getAspectRatio(camera));
  5870. size = { width: width, height: height };
  5871. }
  5872. else if (size.height && !size.width) {
  5873. height = size.height;
  5874. width = Math.round(height * engine.getAspectRatio(camera));
  5875. size = { width: width, height: height };
  5876. }
  5877. else if (!isNaN(size)) {
  5878. height = size;
  5879. width = size;
  5880. }
  5881. else {
  5882. Tools.Error("Invalid 'size' parameter !");
  5883. return;
  5884. }
  5885. var scene = camera.getScene();
  5886. var previousCamera = null;
  5887. if (scene.activeCamera !== camera) {
  5888. previousCamera = scene.activeCamera;
  5889. scene.activeCamera = camera;
  5890. }
  5891. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5892. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  5893. texture.renderList = scene.meshes;
  5894. texture.samples = samples;
  5895. texture.onAfterRenderObservable.add(function () {
  5896. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5897. });
  5898. scene.incrementRenderId();
  5899. scene.resetCachedMaterial();
  5900. texture.render(true);
  5901. texture.dispose();
  5902. if (previousCamera) {
  5903. scene.activeCamera = previousCamera;
  5904. }
  5905. camera.getProjectionMatrix(true); // Force cache refresh;
  5906. };
  5907. // XHR response validator for local file scenario
  5908. Tools.ValidateXHRData = function (xhr, dataType) {
  5909. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5910. if (dataType === void 0) { dataType = 7; }
  5911. try {
  5912. if (dataType & 1) {
  5913. if (xhr.responseText && xhr.responseText.length > 0) {
  5914. return true;
  5915. }
  5916. else if (dataType === 1) {
  5917. return false;
  5918. }
  5919. }
  5920. if (dataType & 2) {
  5921. // Check header width and height since there is no "TGA" magic number
  5922. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5923. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5924. return true;
  5925. }
  5926. else if (dataType === 2) {
  5927. return false;
  5928. }
  5929. }
  5930. if (dataType & 4) {
  5931. // Check for the "DDS" magic number
  5932. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5933. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5934. return true;
  5935. }
  5936. else {
  5937. return false;
  5938. }
  5939. }
  5940. }
  5941. catch (e) {
  5942. // Global protection
  5943. }
  5944. return false;
  5945. };
  5946. /**
  5947. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5948. * Be aware Math.random() could cause collisions, but:
  5949. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  5950. */
  5951. Tools.RandomId = function () {
  5952. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5953. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5954. return v.toString(16);
  5955. });
  5956. };
  5957. Object.defineProperty(Tools, "NoneLogLevel", {
  5958. get: function () {
  5959. return Tools._NoneLogLevel;
  5960. },
  5961. enumerable: true,
  5962. configurable: true
  5963. });
  5964. Object.defineProperty(Tools, "MessageLogLevel", {
  5965. get: function () {
  5966. return Tools._MessageLogLevel;
  5967. },
  5968. enumerable: true,
  5969. configurable: true
  5970. });
  5971. Object.defineProperty(Tools, "WarningLogLevel", {
  5972. get: function () {
  5973. return Tools._WarningLogLevel;
  5974. },
  5975. enumerable: true,
  5976. configurable: true
  5977. });
  5978. Object.defineProperty(Tools, "ErrorLogLevel", {
  5979. get: function () {
  5980. return Tools._ErrorLogLevel;
  5981. },
  5982. enumerable: true,
  5983. configurable: true
  5984. });
  5985. Object.defineProperty(Tools, "AllLogLevel", {
  5986. get: function () {
  5987. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5988. },
  5989. enumerable: true,
  5990. configurable: true
  5991. });
  5992. Tools._AddLogEntry = function (entry) {
  5993. Tools._LogCache = entry + Tools._LogCache;
  5994. if (Tools.OnNewCacheEntry) {
  5995. Tools.OnNewCacheEntry(entry);
  5996. }
  5997. };
  5998. Tools._FormatMessage = function (message) {
  5999. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6000. var date = new Date();
  6001. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6002. };
  6003. Tools._LogDisabled = function (message) {
  6004. // nothing to do
  6005. };
  6006. Tools._LogEnabled = function (message) {
  6007. var formattedMessage = Tools._FormatMessage(message);
  6008. console.log("BJS - " + formattedMessage);
  6009. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6010. Tools._AddLogEntry(entry);
  6011. };
  6012. Tools._WarnDisabled = function (message) {
  6013. // nothing to do
  6014. };
  6015. Tools._WarnEnabled = function (message) {
  6016. var formattedMessage = Tools._FormatMessage(message);
  6017. console.warn("BJS - " + formattedMessage);
  6018. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6019. Tools._AddLogEntry(entry);
  6020. };
  6021. Tools._ErrorDisabled = function (message) {
  6022. // nothing to do
  6023. };
  6024. Tools._ErrorEnabled = function (message) {
  6025. Tools.errorsCount++;
  6026. var formattedMessage = Tools._FormatMessage(message);
  6027. console.error("BJS - " + formattedMessage);
  6028. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6029. Tools._AddLogEntry(entry);
  6030. };
  6031. Object.defineProperty(Tools, "LogCache", {
  6032. get: function () {
  6033. return Tools._LogCache;
  6034. },
  6035. enumerable: true,
  6036. configurable: true
  6037. });
  6038. Tools.ClearLogCache = function () {
  6039. Tools._LogCache = "";
  6040. Tools.errorsCount = 0;
  6041. };
  6042. Object.defineProperty(Tools, "LogLevels", {
  6043. set: function (level) {
  6044. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6045. Tools.Log = Tools._LogEnabled;
  6046. }
  6047. else {
  6048. Tools.Log = Tools._LogDisabled;
  6049. }
  6050. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6051. Tools.Warn = Tools._WarnEnabled;
  6052. }
  6053. else {
  6054. Tools.Warn = Tools._WarnDisabled;
  6055. }
  6056. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6057. Tools.Error = Tools._ErrorEnabled;
  6058. }
  6059. else {
  6060. Tools.Error = Tools._ErrorDisabled;
  6061. }
  6062. },
  6063. enumerable: true,
  6064. configurable: true
  6065. });
  6066. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6067. get: function () {
  6068. return Tools._PerformanceNoneLogLevel;
  6069. },
  6070. enumerable: true,
  6071. configurable: true
  6072. });
  6073. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6074. get: function () {
  6075. return Tools._PerformanceUserMarkLogLevel;
  6076. },
  6077. enumerable: true,
  6078. configurable: true
  6079. });
  6080. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6081. get: function () {
  6082. return Tools._PerformanceConsoleLogLevel;
  6083. },
  6084. enumerable: true,
  6085. configurable: true
  6086. });
  6087. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6088. set: function (level) {
  6089. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6090. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6091. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6092. return;
  6093. }
  6094. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6095. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6096. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6097. return;
  6098. }
  6099. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6100. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6101. },
  6102. enumerable: true,
  6103. configurable: true
  6104. });
  6105. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6106. };
  6107. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6108. };
  6109. Tools._StartUserMark = function (counterName, condition) {
  6110. if (condition === void 0) { condition = true; }
  6111. if (!condition || !Tools._performance.mark) {
  6112. return;
  6113. }
  6114. Tools._performance.mark(counterName + "-Begin");
  6115. };
  6116. Tools._EndUserMark = function (counterName, condition) {
  6117. if (condition === void 0) { condition = true; }
  6118. if (!condition || !Tools._performance.mark) {
  6119. return;
  6120. }
  6121. Tools._performance.mark(counterName + "-End");
  6122. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6123. };
  6124. Tools._StartPerformanceConsole = function (counterName, condition) {
  6125. if (condition === void 0) { condition = true; }
  6126. if (!condition) {
  6127. return;
  6128. }
  6129. Tools._StartUserMark(counterName, condition);
  6130. if (console.time) {
  6131. console.time(counterName);
  6132. }
  6133. };
  6134. Tools._EndPerformanceConsole = function (counterName, condition) {
  6135. if (condition === void 0) { condition = true; }
  6136. if (!condition) {
  6137. return;
  6138. }
  6139. Tools._EndUserMark(counterName, condition);
  6140. if (console.time) {
  6141. console.timeEnd(counterName);
  6142. }
  6143. };
  6144. Object.defineProperty(Tools, "Now", {
  6145. get: function () {
  6146. if (window.performance && window.performance.now) {
  6147. return window.performance.now();
  6148. }
  6149. return new Date().getTime();
  6150. },
  6151. enumerable: true,
  6152. configurable: true
  6153. });
  6154. /**
  6155. * This method will return the name of the class used to create the instance of the given object.
  6156. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6157. * @param object the object to get the class name from
  6158. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6159. */
  6160. Tools.getClassName = function (object, isType) {
  6161. if (isType === void 0) { isType = false; }
  6162. var name = null;
  6163. if (!isType && object.getClassName) {
  6164. name = object.getClassName();
  6165. }
  6166. else {
  6167. if (object instanceof Object) {
  6168. var classObj = isType ? object : Object.getPrototypeOf(object);
  6169. name = classObj.constructor["__bjsclassName__"];
  6170. }
  6171. if (!name) {
  6172. name = typeof object;
  6173. }
  6174. }
  6175. return name;
  6176. };
  6177. Tools.first = function (array, predicate) {
  6178. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6179. var el = array_1[_i];
  6180. if (predicate(el)) {
  6181. return el;
  6182. }
  6183. }
  6184. };
  6185. /**
  6186. * This method will return the name of the full name of the class, including its owning module (if any).
  6187. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).
  6188. * @param object the object to get the class name from
  6189. * @return a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified.
  6190. */
  6191. Tools.getFullClassName = function (object, isType) {
  6192. if (isType === void 0) { isType = false; }
  6193. var className = null;
  6194. var moduleName = null;
  6195. if (!isType && object.getClassName) {
  6196. className = object.getClassName();
  6197. }
  6198. else {
  6199. if (object instanceof Object) {
  6200. var classObj = isType ? object : Object.getPrototypeOf(object);
  6201. className = classObj.constructor["__bjsclassName__"];
  6202. moduleName = classObj.constructor["__bjsmoduleName__"];
  6203. }
  6204. if (!className) {
  6205. className = typeof object;
  6206. }
  6207. }
  6208. if (!className) {
  6209. return null;
  6210. }
  6211. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6212. };
  6213. /**
  6214. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  6215. * @param array
  6216. */
  6217. Tools.arrayOrStringFeeder = function (array) {
  6218. return function (index) {
  6219. if (index >= array.length) {
  6220. return null;
  6221. }
  6222. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6223. if (val && val.getHashCode) {
  6224. val = val.getHashCode();
  6225. }
  6226. if (typeof val === "string") {
  6227. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6228. }
  6229. return val;
  6230. };
  6231. };
  6232. /**
  6233. * Compute the hashCode of a stream of number
  6234. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6235. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6236. * @return the hash code computed
  6237. */
  6238. Tools.hashCodeFromStream = function (feeder) {
  6239. // Based from here: http://stackoverflow.com/a/7616484/802124
  6240. var hash = 0;
  6241. var index = 0;
  6242. var chr = feeder(index++);
  6243. while (chr != null) {
  6244. hash = ((hash << 5) - hash) + chr;
  6245. hash |= 0; // Convert to 32bit integer
  6246. chr = feeder(index++);
  6247. }
  6248. return hash;
  6249. };
  6250. return Tools;
  6251. }());
  6252. Tools.BaseUrl = "";
  6253. Tools.CorsBehavior = "anonymous";
  6254. Tools.UseFallbackTexture = true;
  6255. // Used in case of a texture loading problem
  6256. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  6257. // Logs
  6258. Tools._NoneLogLevel = 0;
  6259. Tools._MessageLogLevel = 1;
  6260. Tools._WarningLogLevel = 2;
  6261. Tools._ErrorLogLevel = 4;
  6262. Tools._LogCache = "";
  6263. Tools.errorsCount = 0;
  6264. Tools.Log = Tools._LogEnabled;
  6265. Tools.Warn = Tools._WarnEnabled;
  6266. Tools.Error = Tools._ErrorEnabled;
  6267. // Performances
  6268. Tools._PerformanceNoneLogLevel = 0;
  6269. Tools._PerformanceUserMarkLogLevel = 1;
  6270. Tools._PerformanceConsoleLogLevel = 2;
  6271. Tools._performance = window.performance;
  6272. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6273. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6274. BABYLON.Tools = Tools;
  6275. /**
  6276. * This class is used to track a performance counter which is number based.
  6277. * The user has access to many properties which give statistics of different nature
  6278. *
  6279. * The implementer can track two kinds of Performance Counter: time and count
  6280. * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
  6281. * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
  6282. */
  6283. var PerfCounter = (function () {
  6284. function PerfCounter() {
  6285. this._startMonitoringTime = 0;
  6286. this._min = 0;
  6287. this._max = 0;
  6288. this._average = 0;
  6289. this._lastSecAverage = 0;
  6290. this._current = 0;
  6291. this._totalValueCount = 0;
  6292. this._totalAccumulated = 0;
  6293. this._lastSecAccumulated = 0;
  6294. this._lastSecTime = 0;
  6295. this._lastSecValueCount = 0;
  6296. }
  6297. Object.defineProperty(PerfCounter.prototype, "min", {
  6298. /**
  6299. * Returns the smallest value ever
  6300. */
  6301. get: function () {
  6302. return this._min;
  6303. },
  6304. enumerable: true,
  6305. configurable: true
  6306. });
  6307. Object.defineProperty(PerfCounter.prototype, "max", {
  6308. /**
  6309. * Returns the biggest value ever
  6310. */
  6311. get: function () {
  6312. return this._max;
  6313. },
  6314. enumerable: true,
  6315. configurable: true
  6316. });
  6317. Object.defineProperty(PerfCounter.prototype, "average", {
  6318. /**
  6319. * Returns the average value since the performance counter is running
  6320. */
  6321. get: function () {
  6322. return this._average;
  6323. },
  6324. enumerable: true,
  6325. configurable: true
  6326. });
  6327. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6328. /**
  6329. * Returns the average value of the last second the counter was monitored
  6330. */
  6331. get: function () {
  6332. return this._lastSecAverage;
  6333. },
  6334. enumerable: true,
  6335. configurable: true
  6336. });
  6337. Object.defineProperty(PerfCounter.prototype, "current", {
  6338. /**
  6339. * Returns the current value
  6340. */
  6341. get: function () {
  6342. return this._current;
  6343. },
  6344. enumerable: true,
  6345. configurable: true
  6346. });
  6347. Object.defineProperty(PerfCounter.prototype, "total", {
  6348. get: function () {
  6349. return this._totalAccumulated;
  6350. },
  6351. enumerable: true,
  6352. configurable: true
  6353. });
  6354. /**
  6355. * Call this method to start monitoring a new frame.
  6356. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
  6357. */
  6358. PerfCounter.prototype.fetchNewFrame = function () {
  6359. this._totalValueCount++;
  6360. this._current = 0;
  6361. this._lastSecValueCount++;
  6362. };
  6363. /**
  6364. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6365. * @param newCount the count value to add to the monitored count
  6366. * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
  6367. */
  6368. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6369. if (!PerfCounter.Enabled) {
  6370. return;
  6371. }
  6372. this._current += newCount;
  6373. if (fetchResult) {
  6374. this._fetchResult();
  6375. }
  6376. };
  6377. /**
  6378. * Start monitoring this performance counter
  6379. */
  6380. PerfCounter.prototype.beginMonitoring = function () {
  6381. if (!PerfCounter.Enabled) {
  6382. return;
  6383. }
  6384. this._startMonitoringTime = Tools.Now;
  6385. };
  6386. /**
  6387. * Compute the time lapsed since the previous beginMonitoring() call.
  6388. * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
  6389. */
  6390. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6391. if (newFrame === void 0) { newFrame = true; }
  6392. if (!PerfCounter.Enabled) {
  6393. return;
  6394. }
  6395. if (newFrame) {
  6396. this.fetchNewFrame();
  6397. }
  6398. var currentTime = Tools.Now;
  6399. this._current = currentTime - this._startMonitoringTime;
  6400. if (newFrame) {
  6401. this._fetchResult();
  6402. }
  6403. };
  6404. PerfCounter.prototype._fetchResult = function () {
  6405. this._totalAccumulated += this._current;
  6406. this._lastSecAccumulated += this._current;
  6407. // Min/Max update
  6408. this._min = Math.min(this._min, this._current);
  6409. this._max = Math.max(this._max, this._current);
  6410. this._average = this._totalAccumulated / this._totalValueCount;
  6411. // Reset last sec?
  6412. var now = Tools.Now;
  6413. if ((now - this._lastSecTime) > 1000) {
  6414. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6415. this._lastSecTime = now;
  6416. this._lastSecAccumulated = 0;
  6417. this._lastSecValueCount = 0;
  6418. }
  6419. };
  6420. return PerfCounter;
  6421. }());
  6422. PerfCounter.Enabled = true;
  6423. BABYLON.PerfCounter = PerfCounter;
  6424. /**
  6425. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6426. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6427. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6428. * @param name The name of the class, case should be preserved
  6429. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6430. */
  6431. function className(name, module) {
  6432. return function (target) {
  6433. target["__bjsclassName__"] = name;
  6434. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6435. };
  6436. }
  6437. BABYLON.className = className;
  6438. /**
  6439. * An implementation of a loop for asynchronous functions.
  6440. */
  6441. var AsyncLoop = (function () {
  6442. /**
  6443. * Constroctor.
  6444. * @param iterations the number of iterations.
  6445. * @param _fn the function to run each iteration
  6446. * @param _successCallback the callback that will be called upon succesful execution
  6447. * @param offset starting offset.
  6448. */
  6449. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6450. if (offset === void 0) { offset = 0; }
  6451. this.iterations = iterations;
  6452. this._fn = _fn;
  6453. this._successCallback = _successCallback;
  6454. this.index = offset - 1;
  6455. this._done = false;
  6456. }
  6457. /**
  6458. * Execute the next iteration. Must be called after the last iteration was finished.
  6459. */
  6460. AsyncLoop.prototype.executeNext = function () {
  6461. if (!this._done) {
  6462. if (this.index + 1 < this.iterations) {
  6463. ++this.index;
  6464. this._fn(this);
  6465. }
  6466. else {
  6467. this.breakLoop();
  6468. }
  6469. }
  6470. };
  6471. /**
  6472. * Break the loop and run the success callback.
  6473. */
  6474. AsyncLoop.prototype.breakLoop = function () {
  6475. this._done = true;
  6476. this._successCallback();
  6477. };
  6478. /**
  6479. * Helper function
  6480. */
  6481. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6482. if (offset === void 0) { offset = 0; }
  6483. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6484. loop.executeNext();
  6485. return loop;
  6486. };
  6487. /**
  6488. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6489. * @param iterations total number of iterations
  6490. * @param syncedIterations number of synchronous iterations in each async iteration.
  6491. * @param fn the function to call each iteration.
  6492. * @param callback a success call back that will be called when iterating stops.
  6493. * @param breakFunction a break condition (optional)
  6494. * @param timeout timeout settings for the setTimeout function. default - 0.
  6495. * @constructor
  6496. */
  6497. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6498. if (timeout === void 0) { timeout = 0; }
  6499. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6500. if (breakFunction && breakFunction())
  6501. loop.breakLoop();
  6502. else {
  6503. setTimeout(function () {
  6504. for (var i = 0; i < syncedIterations; ++i) {
  6505. var iteration = (loop.index * syncedIterations) + i;
  6506. if (iteration >= iterations)
  6507. break;
  6508. fn(iteration);
  6509. if (breakFunction && breakFunction()) {
  6510. loop.breakLoop();
  6511. break;
  6512. }
  6513. }
  6514. loop.executeNext();
  6515. }, timeout);
  6516. }
  6517. }, callback);
  6518. };
  6519. return AsyncLoop;
  6520. }());
  6521. BABYLON.AsyncLoop = AsyncLoop;
  6522. })(BABYLON || (BABYLON = {}));
  6523. //# sourceMappingURL=babylon.tools.js.map
  6524. var BABYLON;
  6525. (function (BABYLON) {
  6526. var Internals;
  6527. (function (Internals) {
  6528. var _AlphaState = (function () {
  6529. /**
  6530. * Initializes the state.
  6531. */
  6532. function _AlphaState() {
  6533. this._isAlphaBlendDirty = false;
  6534. this._isBlendFunctionParametersDirty = false;
  6535. this._isBlendEquationParametersDirty = false;
  6536. this._isBlendConstantsDirty = false;
  6537. this._alphaBlend = false;
  6538. this._blendFunctionParameters = new Array(4);
  6539. this._blendEquationParameters = new Array(2);
  6540. this._blendConstants = new Array(4);
  6541. this.reset();
  6542. }
  6543. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6544. get: function () {
  6545. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6546. },
  6547. enumerable: true,
  6548. configurable: true
  6549. });
  6550. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6551. get: function () {
  6552. return this._alphaBlend;
  6553. },
  6554. set: function (value) {
  6555. if (this._alphaBlend === value) {
  6556. return;
  6557. }
  6558. this._alphaBlend = value;
  6559. this._isAlphaBlendDirty = true;
  6560. },
  6561. enumerable: true,
  6562. configurable: true
  6563. });
  6564. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  6565. if (this._blendConstants[0] === r &&
  6566. this._blendConstants[1] === g &&
  6567. this._blendConstants[2] === b &&
  6568. this._blendConstants[3] === a) {
  6569. return;
  6570. }
  6571. this._blendConstants[0] = r;
  6572. this._blendConstants[1] = g;
  6573. this._blendConstants[2] = b;
  6574. this._blendConstants[3] = a;
  6575. this._isBlendConstantsDirty = true;
  6576. };
  6577. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6578. if (this._blendFunctionParameters[0] === value0 &&
  6579. this._blendFunctionParameters[1] === value1 &&
  6580. this._blendFunctionParameters[2] === value2 &&
  6581. this._blendFunctionParameters[3] === value3) {
  6582. return;
  6583. }
  6584. this._blendFunctionParameters[0] = value0;
  6585. this._blendFunctionParameters[1] = value1;
  6586. this._blendFunctionParameters[2] = value2;
  6587. this._blendFunctionParameters[3] = value3;
  6588. this._isBlendFunctionParametersDirty = true;
  6589. };
  6590. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  6591. if (this._blendEquationParameters[0] === rgb &&
  6592. this._blendEquationParameters[1] === alpha) {
  6593. return;
  6594. }
  6595. this._blendEquationParameters[0] = rgb;
  6596. this._blendEquationParameters[1] = alpha;
  6597. this._isBlendEquationParametersDirty = true;
  6598. };
  6599. _AlphaState.prototype.reset = function () {
  6600. this._alphaBlend = false;
  6601. this._blendFunctionParameters[0] = null;
  6602. this._blendFunctionParameters[1] = null;
  6603. this._blendFunctionParameters[2] = null;
  6604. this._blendFunctionParameters[3] = null;
  6605. this._blendEquationParameters[0] = null;
  6606. this._blendEquationParameters[1] = null;
  6607. this._blendConstants[0] = null;
  6608. this._blendConstants[1] = null;
  6609. this._blendConstants[2] = null;
  6610. this._blendConstants[3] = null;
  6611. this._isAlphaBlendDirty = true;
  6612. this._isBlendFunctionParametersDirty = false;
  6613. this._isBlendEquationParametersDirty = false;
  6614. this._isBlendConstantsDirty = false;
  6615. };
  6616. _AlphaState.prototype.apply = function (gl) {
  6617. if (!this.isDirty) {
  6618. return;
  6619. }
  6620. // Alpha blend
  6621. if (this._isAlphaBlendDirty) {
  6622. if (this._alphaBlend) {
  6623. gl.enable(gl.BLEND);
  6624. }
  6625. else {
  6626. gl.disable(gl.BLEND);
  6627. }
  6628. this._isAlphaBlendDirty = false;
  6629. }
  6630. // Alpha function
  6631. if (this._isBlendFunctionParametersDirty) {
  6632. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6633. this._isBlendFunctionParametersDirty = false;
  6634. }
  6635. // Alpha equation
  6636. if (this._isBlendEquationParametersDirty) {
  6637. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  6638. this._isBlendEquationParametersDirty = false;
  6639. }
  6640. // Constants
  6641. if (this._isBlendConstantsDirty) {
  6642. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  6643. this._isBlendConstantsDirty = false;
  6644. }
  6645. };
  6646. return _AlphaState;
  6647. }());
  6648. Internals._AlphaState = _AlphaState;
  6649. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6650. })(BABYLON || (BABYLON = {}));
  6651. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6652. var BABYLON;
  6653. (function (BABYLON) {
  6654. var Internals;
  6655. (function (Internals) {
  6656. var _DepthCullingState = (function () {
  6657. /**
  6658. * Initializes the state.
  6659. */
  6660. function _DepthCullingState() {
  6661. this._isDepthTestDirty = false;
  6662. this._isDepthMaskDirty = false;
  6663. this._isDepthFuncDirty = false;
  6664. this._isCullFaceDirty = false;
  6665. this._isCullDirty = false;
  6666. this._isZOffsetDirty = false;
  6667. this.reset();
  6668. }
  6669. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6670. get: function () {
  6671. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6672. },
  6673. enumerable: true,
  6674. configurable: true
  6675. });
  6676. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6677. get: function () {
  6678. return this._zOffset;
  6679. },
  6680. set: function (value) {
  6681. if (this._zOffset === value) {
  6682. return;
  6683. }
  6684. this._zOffset = value;
  6685. this._isZOffsetDirty = true;
  6686. },
  6687. enumerable: true,
  6688. configurable: true
  6689. });
  6690. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6691. get: function () {
  6692. return this._cullFace;
  6693. },
  6694. set: function (value) {
  6695. if (this._cullFace === value) {
  6696. return;
  6697. }
  6698. this._cullFace = value;
  6699. this._isCullFaceDirty = true;
  6700. },
  6701. enumerable: true,
  6702. configurable: true
  6703. });
  6704. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6705. get: function () {
  6706. return this._cull;
  6707. },
  6708. set: function (value) {
  6709. if (this._cull === value) {
  6710. return;
  6711. }
  6712. this._cull = value;
  6713. this._isCullDirty = true;
  6714. },
  6715. enumerable: true,
  6716. configurable: true
  6717. });
  6718. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6719. get: function () {
  6720. return this._depthFunc;
  6721. },
  6722. set: function (value) {
  6723. if (this._depthFunc === value) {
  6724. return;
  6725. }
  6726. this._depthFunc = value;
  6727. this._isDepthFuncDirty = true;
  6728. },
  6729. enumerable: true,
  6730. configurable: true
  6731. });
  6732. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6733. get: function () {
  6734. return this._depthMask;
  6735. },
  6736. set: function (value) {
  6737. if (this._depthMask === value) {
  6738. return;
  6739. }
  6740. this._depthMask = value;
  6741. this._isDepthMaskDirty = true;
  6742. },
  6743. enumerable: true,
  6744. configurable: true
  6745. });
  6746. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6747. get: function () {
  6748. return this._depthTest;
  6749. },
  6750. set: function (value) {
  6751. if (this._depthTest === value) {
  6752. return;
  6753. }
  6754. this._depthTest = value;
  6755. this._isDepthTestDirty = true;
  6756. },
  6757. enumerable: true,
  6758. configurable: true
  6759. });
  6760. _DepthCullingState.prototype.reset = function () {
  6761. this._depthMask = true;
  6762. this._depthTest = true;
  6763. this._depthFunc = null;
  6764. this._cullFace = null;
  6765. this._cull = null;
  6766. this._zOffset = 0;
  6767. this._isDepthTestDirty = true;
  6768. this._isDepthMaskDirty = true;
  6769. this._isDepthFuncDirty = false;
  6770. this._isCullFaceDirty = false;
  6771. this._isCullDirty = false;
  6772. this._isZOffsetDirty = false;
  6773. };
  6774. _DepthCullingState.prototype.apply = function (gl) {
  6775. if (!this.isDirty) {
  6776. return;
  6777. }
  6778. // Cull
  6779. if (this._isCullDirty) {
  6780. if (this.cull) {
  6781. gl.enable(gl.CULL_FACE);
  6782. }
  6783. else {
  6784. gl.disable(gl.CULL_FACE);
  6785. }
  6786. this._isCullDirty = false;
  6787. }
  6788. // Cull face
  6789. if (this._isCullFaceDirty) {
  6790. gl.cullFace(this.cullFace);
  6791. this._isCullFaceDirty = false;
  6792. }
  6793. // Depth mask
  6794. if (this._isDepthMaskDirty) {
  6795. gl.depthMask(this.depthMask);
  6796. this._isDepthMaskDirty = false;
  6797. }
  6798. // Depth test
  6799. if (this._isDepthTestDirty) {
  6800. if (this.depthTest) {
  6801. gl.enable(gl.DEPTH_TEST);
  6802. }
  6803. else {
  6804. gl.disable(gl.DEPTH_TEST);
  6805. }
  6806. this._isDepthTestDirty = false;
  6807. }
  6808. // Depth func
  6809. if (this._isDepthFuncDirty) {
  6810. gl.depthFunc(this.depthFunc);
  6811. this._isDepthFuncDirty = false;
  6812. }
  6813. // zOffset
  6814. if (this._isZOffsetDirty) {
  6815. if (this.zOffset) {
  6816. gl.enable(gl.POLYGON_OFFSET_FILL);
  6817. gl.polygonOffset(this.zOffset, 0);
  6818. }
  6819. else {
  6820. gl.disable(gl.POLYGON_OFFSET_FILL);
  6821. }
  6822. this._isZOffsetDirty = false;
  6823. }
  6824. };
  6825. return _DepthCullingState;
  6826. }());
  6827. Internals._DepthCullingState = _DepthCullingState;
  6828. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6829. })(BABYLON || (BABYLON = {}));
  6830. //# sourceMappingURL=babylon.depthCullingState.js.map
  6831. var BABYLON;
  6832. (function (BABYLON) {
  6833. var Internals;
  6834. (function (Internals) {
  6835. var _StencilState = (function () {
  6836. function _StencilState() {
  6837. this._isStencilTestDirty = false;
  6838. this._isStencilMaskDirty = false;
  6839. this._isStencilFuncDirty = false;
  6840. this._isStencilOpDirty = false;
  6841. this.reset();
  6842. }
  6843. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6844. get: function () {
  6845. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6846. },
  6847. enumerable: true,
  6848. configurable: true
  6849. });
  6850. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6851. get: function () {
  6852. return this._stencilFunc;
  6853. },
  6854. set: function (value) {
  6855. if (this._stencilFunc === value) {
  6856. return;
  6857. }
  6858. this._stencilFunc = value;
  6859. this._isStencilFuncDirty = true;
  6860. },
  6861. enumerable: true,
  6862. configurable: true
  6863. });
  6864. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6865. get: function () {
  6866. return this._stencilFuncRef;
  6867. },
  6868. set: function (value) {
  6869. if (this._stencilFuncRef === value) {
  6870. return;
  6871. }
  6872. this._stencilFuncRef = value;
  6873. this._isStencilFuncDirty = true;
  6874. },
  6875. enumerable: true,
  6876. configurable: true
  6877. });
  6878. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6879. get: function () {
  6880. return this._stencilFuncMask;
  6881. },
  6882. set: function (value) {
  6883. if (this._stencilFuncMask === value) {
  6884. return;
  6885. }
  6886. this._stencilFuncMask = value;
  6887. this._isStencilFuncDirty = true;
  6888. },
  6889. enumerable: true,
  6890. configurable: true
  6891. });
  6892. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6893. get: function () {
  6894. return this._stencilOpStencilFail;
  6895. },
  6896. set: function (value) {
  6897. if (this._stencilOpStencilFail === value) {
  6898. return;
  6899. }
  6900. this._stencilOpStencilFail = value;
  6901. this._isStencilOpDirty = true;
  6902. },
  6903. enumerable: true,
  6904. configurable: true
  6905. });
  6906. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6907. get: function () {
  6908. return this._stencilOpDepthFail;
  6909. },
  6910. set: function (value) {
  6911. if (this._stencilOpDepthFail === value) {
  6912. return;
  6913. }
  6914. this._stencilOpDepthFail = value;
  6915. this._isStencilOpDirty = true;
  6916. },
  6917. enumerable: true,
  6918. configurable: true
  6919. });
  6920. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6921. get: function () {
  6922. return this._stencilOpStencilDepthPass;
  6923. },
  6924. set: function (value) {
  6925. if (this._stencilOpStencilDepthPass === value) {
  6926. return;
  6927. }
  6928. this._stencilOpStencilDepthPass = value;
  6929. this._isStencilOpDirty = true;
  6930. },
  6931. enumerable: true,
  6932. configurable: true
  6933. });
  6934. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6935. get: function () {
  6936. return this._stencilMask;
  6937. },
  6938. set: function (value) {
  6939. if (this._stencilMask === value) {
  6940. return;
  6941. }
  6942. this._stencilMask = value;
  6943. this._isStencilMaskDirty = true;
  6944. },
  6945. enumerable: true,
  6946. configurable: true
  6947. });
  6948. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6949. get: function () {
  6950. return this._stencilTest;
  6951. },
  6952. set: function (value) {
  6953. if (this._stencilTest === value) {
  6954. return;
  6955. }
  6956. this._stencilTest = value;
  6957. this._isStencilTestDirty = true;
  6958. },
  6959. enumerable: true,
  6960. configurable: true
  6961. });
  6962. _StencilState.prototype.reset = function () {
  6963. this._stencilTest = false;
  6964. this._stencilMask = 0xFF;
  6965. this._stencilFunc = BABYLON.Engine.ALWAYS;
  6966. this._stencilFuncRef = 1;
  6967. this._stencilFuncMask = 0xFF;
  6968. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  6969. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  6970. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  6971. this._isStencilTestDirty = true;
  6972. this._isStencilMaskDirty = true;
  6973. this._isStencilFuncDirty = true;
  6974. this._isStencilOpDirty = true;
  6975. };
  6976. _StencilState.prototype.apply = function (gl) {
  6977. if (!this.isDirty) {
  6978. return;
  6979. }
  6980. // Stencil test
  6981. if (this._isStencilTestDirty) {
  6982. if (this.stencilTest) {
  6983. gl.enable(gl.STENCIL_TEST);
  6984. }
  6985. else {
  6986. gl.disable(gl.STENCIL_TEST);
  6987. }
  6988. this._isStencilTestDirty = false;
  6989. }
  6990. // Stencil mask
  6991. if (this._isStencilMaskDirty) {
  6992. gl.stencilMask(this.stencilMask);
  6993. this._isStencilMaskDirty = false;
  6994. }
  6995. // Stencil func
  6996. if (this._isStencilFuncDirty) {
  6997. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6998. this._isStencilFuncDirty = false;
  6999. }
  7000. // Stencil op
  7001. if (this._isStencilOpDirty) {
  7002. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7003. this._isStencilOpDirty = false;
  7004. }
  7005. };
  7006. return _StencilState;
  7007. }());
  7008. Internals._StencilState = _StencilState;
  7009. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7010. })(BABYLON || (BABYLON = {}));
  7011. //# sourceMappingURL=babylon.stencilState.js.map
  7012. var BABYLON;
  7013. (function (BABYLON) {
  7014. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7015. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7016. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7017. gl.compileShader(shader);
  7018. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7019. throw new Error(gl.getShaderInfoLog(shader));
  7020. }
  7021. return shader;
  7022. };
  7023. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7024. var magFilter = gl.NEAREST;
  7025. var minFilter = gl.NEAREST;
  7026. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7027. magFilter = gl.LINEAR;
  7028. if (generateMipMaps) {
  7029. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7030. }
  7031. else {
  7032. minFilter = gl.LINEAR;
  7033. }
  7034. }
  7035. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7036. magFilter = gl.LINEAR;
  7037. if (generateMipMaps) {
  7038. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7039. }
  7040. else {
  7041. minFilter = gl.LINEAR;
  7042. }
  7043. }
  7044. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7045. magFilter = gl.NEAREST;
  7046. if (generateMipMaps) {
  7047. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7048. }
  7049. else {
  7050. minFilter = gl.NEAREST;
  7051. }
  7052. }
  7053. return {
  7054. min: minFilter,
  7055. mag: magFilter
  7056. };
  7057. };
  7058. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  7059. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7060. var engine = scene.getEngine();
  7061. if (!engine) {
  7062. return;
  7063. }
  7064. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  7065. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  7066. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7067. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7068. texture._baseWidth = width;
  7069. texture._baseHeight = height;
  7070. texture._width = potWidth;
  7071. texture._height = potHeight;
  7072. texture.isReady = true;
  7073. processFunction(potWidth, potHeight);
  7074. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  7075. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7076. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7077. if (!noMipmap && !isCompressed) {
  7078. gl.generateMipmap(gl.TEXTURE_2D);
  7079. }
  7080. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  7081. engine.resetTextureCache();
  7082. scene._removePendingData(texture);
  7083. texture.onLoadedCallbacks.forEach(function (callback) {
  7084. callback();
  7085. });
  7086. texture.onLoadedCallbacks = [];
  7087. };
  7088. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7089. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7090. var img;
  7091. var onload = function () {
  7092. loadedImages[index] = img;
  7093. loadedImages._internalCount++;
  7094. scene._removePendingData(img);
  7095. if (loadedImages._internalCount === 6) {
  7096. onfinish(loadedImages);
  7097. }
  7098. };
  7099. var onerror = function () {
  7100. scene._removePendingData(img);
  7101. if (onErrorCallBack) {
  7102. onErrorCallBack();
  7103. }
  7104. };
  7105. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7106. scene._addPendingData(img);
  7107. };
  7108. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7109. if (onError === void 0) { onError = null; }
  7110. var loadedImages = [];
  7111. loadedImages._internalCount = 0;
  7112. for (var index = 0; index < 6; index++) {
  7113. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7114. }
  7115. };
  7116. var InstancingAttributeInfo = (function () {
  7117. function InstancingAttributeInfo() {
  7118. }
  7119. return InstancingAttributeInfo;
  7120. }());
  7121. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7122. var EngineCapabilities = (function () {
  7123. function EngineCapabilities() {
  7124. }
  7125. return EngineCapabilities;
  7126. }());
  7127. BABYLON.EngineCapabilities = EngineCapabilities;
  7128. /**
  7129. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7130. */
  7131. var Engine = (function () {
  7132. /**
  7133. * @constructor
  7134. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  7135. * @param {boolean} [antialias] - enable antialias
  7136. * @param options - further options to be sent to the getContext function
  7137. */
  7138. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  7139. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7140. var _this = this;
  7141. // Public members
  7142. this.isFullscreen = false;
  7143. this.isPointerLock = false;
  7144. this.cullBackFaces = true;
  7145. this.renderEvenInBackground = true;
  7146. this.preventCacheWipeBetweenFrames = false;
  7147. // To enable/disable IDB support and avoid XHR on .manifest
  7148. this.enableOfflineSupport = BABYLON.Database;
  7149. this.scenes = new Array();
  7150. // Observables
  7151. /**
  7152. * Observable event triggered each time the rendering canvas is resized
  7153. */
  7154. this.onResizeObservable = new BABYLON.Observable();
  7155. /**
  7156. * Observable event triggered each time the canvas lost focus
  7157. */
  7158. this.onCanvasBlurObservable = new BABYLON.Observable();
  7159. this._windowIsBackground = false;
  7160. this._webGLVersion = 1.0;
  7161. this._badOS = false;
  7162. this._drawCalls = new BABYLON.PerfCounter();
  7163. this._renderingQueueLaunched = false;
  7164. this._activeRenderLoops = [];
  7165. // FPS
  7166. this.fpsRange = 60;
  7167. this.previousFramesDuration = [];
  7168. this.fps = 60;
  7169. this.deltaTime = 0;
  7170. // States
  7171. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7172. this._stencilState = new BABYLON.Internals._StencilState();
  7173. this._alphaState = new BABYLON.Internals._AlphaState();
  7174. this._alphaMode = Engine.ALPHA_DISABLE;
  7175. // Cache
  7176. this._loadedTexturesCache = new Array();
  7177. this._maxTextureChannels = 16;
  7178. this._activeTexturesCache = new Array(this._maxTextureChannels);
  7179. this._compiledEffects = {};
  7180. this._vertexAttribArraysEnabled = [];
  7181. this._uintIndicesCurrentlySet = false;
  7182. this._currentBoundBuffer = new Array();
  7183. this._currentBufferPointers = [];
  7184. this._currentInstanceLocations = new Array();
  7185. this._currentInstanceBuffers = new Array();
  7186. this._vaoRecordInProgress = false;
  7187. this._mustWipeVertexAttributes = false;
  7188. // Hardware supported Compressed Textures
  7189. this._texturesSupported = new Array();
  7190. this._onVRFullScreenTriggered = function () {
  7191. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7192. //get the old size before we change
  7193. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7194. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7195. //get the width and height, change the render size
  7196. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7197. var width, height;
  7198. _this.setHardwareScalingLevel(1);
  7199. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7200. }
  7201. else {
  7202. //When the specs are implemented, need to uncomment this.
  7203. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7204. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7205. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7206. _this._vrDisplayEnabled = undefined;
  7207. }
  7208. };
  7209. this._renderingCanvas = canvas;
  7210. Engine.Instances.push(this);
  7211. options = options || {};
  7212. if (antialias != null) {
  7213. options.antialias = antialias;
  7214. }
  7215. if (options.preserveDrawingBuffer === undefined) {
  7216. options.preserveDrawingBuffer = false;
  7217. }
  7218. if (options.audioEngine === undefined) {
  7219. options.audioEngine = true;
  7220. }
  7221. if (options.stencil === undefined) {
  7222. options.stencil = true;
  7223. }
  7224. // GL
  7225. if (!options.disableWebGL2Support) {
  7226. try {
  7227. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7228. if (this._gl) {
  7229. this._webGLVersion = 2.0;
  7230. }
  7231. }
  7232. catch (e) {
  7233. // Do nothing
  7234. }
  7235. }
  7236. if (!this._gl) {
  7237. if (!canvas) {
  7238. throw new Error("The provided canvas is null or undefined.");
  7239. }
  7240. try {
  7241. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7242. }
  7243. catch (e) {
  7244. throw new Error("WebGL not supported");
  7245. }
  7246. }
  7247. if (!this._gl) {
  7248. throw new Error("WebGL not supported");
  7249. }
  7250. this._onBlur = function () {
  7251. _this._windowIsBackground = true;
  7252. };
  7253. this._onFocus = function () {
  7254. _this._windowIsBackground = false;
  7255. };
  7256. this._onCanvasBlur = function () {
  7257. _this.onCanvasBlurObservable.notifyObservers(_this);
  7258. };
  7259. window.addEventListener("blur", this._onBlur);
  7260. window.addEventListener("focus", this._onFocus);
  7261. canvas.addEventListener("pointerout", this._onCanvasBlur);
  7262. // Viewport
  7263. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7264. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7265. this.resize();
  7266. // Caps
  7267. this._isStencilEnable = options.stencil;
  7268. this._caps = new EngineCapabilities();
  7269. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  7270. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  7271. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  7272. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  7273. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  7274. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  7275. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  7276. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  7277. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  7278. // Infos
  7279. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  7280. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  7281. if (rendererInfo != null) {
  7282. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  7283. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  7284. }
  7285. if (!this._glVendor) {
  7286. this._glVendor = "Unknown vendor";
  7287. }
  7288. if (!this._glRenderer) {
  7289. this._glRenderer = "Unknown renderer";
  7290. }
  7291. // Extensions
  7292. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  7293. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  7294. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  7295. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  7296. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  7297. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  7298. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  7299. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  7300. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  7301. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  7302. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  7303. this._caps.highPrecisionShaderSupported = true;
  7304. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  7305. // Checks if some of the format renders first to allow the use of webgl inspector.
  7306. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  7307. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  7308. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  7309. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  7310. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  7311. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  7312. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  7313. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  7314. // Vertex array object
  7315. if (this._webGLVersion > 1) {
  7316. this._caps.vertexArrayObject = true;
  7317. }
  7318. else {
  7319. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  7320. if (vertexArrayObjectExtension != null) {
  7321. this._caps.vertexArrayObject = true;
  7322. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  7323. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  7324. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  7325. }
  7326. else {
  7327. this._caps.vertexArrayObject = false;
  7328. }
  7329. }
  7330. // Instances count
  7331. if (this._webGLVersion > 1) {
  7332. this._caps.instancedArrays = true;
  7333. }
  7334. else {
  7335. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  7336. if (instanceExtension != null) {
  7337. this._caps.instancedArrays = true;
  7338. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  7339. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  7340. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  7341. }
  7342. else {
  7343. this._caps.instancedArrays = false;
  7344. }
  7345. }
  7346. // Intelligently add supported compressed formats in order to check for.
  7347. // Check for ASTC support first as it is most powerful and to be very cross platform.
  7348. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  7349. // Likely no hardware which supports both PVR & DXT, so order matters little.
  7350. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  7351. if (this._caps.astc)
  7352. this.texturesSupported.push('-astc.ktx');
  7353. if (this._caps.s3tc)
  7354. this.texturesSupported.push('-dxt.ktx');
  7355. if (this._caps.pvrtc)
  7356. this.texturesSupported.push('-pvrtc.ktx');
  7357. if (this._caps.etc2)
  7358. this.texturesSupported.push('-etc2.ktx');
  7359. if (this._caps.etc1)
  7360. this.texturesSupported.push('-etc1.ktx');
  7361. if (this._gl.getShaderPrecisionFormat) {
  7362. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  7363. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  7364. }
  7365. // Depth buffer
  7366. this.setDepthBuffer(true);
  7367. this.setDepthFunctionToLessOrEqual();
  7368. this.setDepthWrite(true);
  7369. // Fullscreen
  7370. this._onFullscreenChange = function () {
  7371. if (document.fullscreen !== undefined) {
  7372. _this.isFullscreen = document.fullscreen;
  7373. }
  7374. else if (document.mozFullScreen !== undefined) {
  7375. _this.isFullscreen = document.mozFullScreen;
  7376. }
  7377. else if (document.webkitIsFullScreen !== undefined) {
  7378. _this.isFullscreen = document.webkitIsFullScreen;
  7379. }
  7380. else if (document.msIsFullScreen !== undefined) {
  7381. _this.isFullscreen = document.msIsFullScreen;
  7382. }
  7383. // Pointer lock
  7384. if (_this.isFullscreen && _this._pointerLockRequested) {
  7385. canvas.requestPointerLock = canvas.requestPointerLock ||
  7386. canvas.msRequestPointerLock ||
  7387. canvas.mozRequestPointerLock ||
  7388. canvas.webkitRequestPointerLock;
  7389. if (canvas.requestPointerLock) {
  7390. canvas.requestPointerLock();
  7391. }
  7392. }
  7393. };
  7394. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7395. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7396. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7397. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7398. // Pointer lock
  7399. this._onPointerLockChange = function () {
  7400. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7401. document.webkitPointerLockElement === canvas ||
  7402. document.msPointerLockElement === canvas ||
  7403. document.pointerLockElement === canvas);
  7404. };
  7405. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7406. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7407. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7408. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7409. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7410. Engine.audioEngine = new BABYLON.AudioEngine();
  7411. }
  7412. //Load WebVR Devices
  7413. if (options.autoEnableWebVR) {
  7414. this.initWebVR();
  7415. }
  7416. //Detect if we are running on a faulty buggy OS.
  7417. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  7418. //ua sniffing is the tool of the devil.
  7419. this._badOS = regexp.test(navigator.userAgent);
  7420. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7421. }
  7422. Object.defineProperty(Engine, "LastCreatedEngine", {
  7423. get: function () {
  7424. if (Engine.Instances.length === 0) {
  7425. return null;
  7426. }
  7427. return Engine.Instances[Engine.Instances.length - 1];
  7428. },
  7429. enumerable: true,
  7430. configurable: true
  7431. });
  7432. Object.defineProperty(Engine, "LastCreatedScene", {
  7433. get: function () {
  7434. var lastCreatedEngine = Engine.LastCreatedEngine;
  7435. if (!lastCreatedEngine) {
  7436. return null;
  7437. }
  7438. if (lastCreatedEngine.scenes.length === 0) {
  7439. return null;
  7440. }
  7441. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7442. },
  7443. enumerable: true,
  7444. configurable: true
  7445. });
  7446. /**
  7447. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7448. */
  7449. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7450. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7451. var engine = Engine.Instances[engineIndex];
  7452. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7453. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7454. }
  7455. }
  7456. };
  7457. Object.defineProperty(Engine, "NEVER", {
  7458. get: function () {
  7459. return Engine._NEVER;
  7460. },
  7461. enumerable: true,
  7462. configurable: true
  7463. });
  7464. Object.defineProperty(Engine, "ALWAYS", {
  7465. get: function () {
  7466. return Engine._ALWAYS;
  7467. },
  7468. enumerable: true,
  7469. configurable: true
  7470. });
  7471. Object.defineProperty(Engine, "LESS", {
  7472. get: function () {
  7473. return Engine._LESS;
  7474. },
  7475. enumerable: true,
  7476. configurable: true
  7477. });
  7478. Object.defineProperty(Engine, "EQUAL", {
  7479. get: function () {
  7480. return Engine._EQUAL;
  7481. },
  7482. enumerable: true,
  7483. configurable: true
  7484. });
  7485. Object.defineProperty(Engine, "LEQUAL", {
  7486. get: function () {
  7487. return Engine._LEQUAL;
  7488. },
  7489. enumerable: true,
  7490. configurable: true
  7491. });
  7492. Object.defineProperty(Engine, "GREATER", {
  7493. get: function () {
  7494. return Engine._GREATER;
  7495. },
  7496. enumerable: true,
  7497. configurable: true
  7498. });
  7499. Object.defineProperty(Engine, "GEQUAL", {
  7500. get: function () {
  7501. return Engine._GEQUAL;
  7502. },
  7503. enumerable: true,
  7504. configurable: true
  7505. });
  7506. Object.defineProperty(Engine, "NOTEQUAL", {
  7507. get: function () {
  7508. return Engine._NOTEQUAL;
  7509. },
  7510. enumerable: true,
  7511. configurable: true
  7512. });
  7513. Object.defineProperty(Engine, "KEEP", {
  7514. get: function () {
  7515. return Engine._KEEP;
  7516. },
  7517. enumerable: true,
  7518. configurable: true
  7519. });
  7520. Object.defineProperty(Engine, "REPLACE", {
  7521. get: function () {
  7522. return Engine._REPLACE;
  7523. },
  7524. enumerable: true,
  7525. configurable: true
  7526. });
  7527. Object.defineProperty(Engine, "INCR", {
  7528. get: function () {
  7529. return Engine._INCR;
  7530. },
  7531. enumerable: true,
  7532. configurable: true
  7533. });
  7534. Object.defineProperty(Engine, "DECR", {
  7535. get: function () {
  7536. return Engine._DECR;
  7537. },
  7538. enumerable: true,
  7539. configurable: true
  7540. });
  7541. Object.defineProperty(Engine, "INVERT", {
  7542. get: function () {
  7543. return Engine._INVERT;
  7544. },
  7545. enumerable: true,
  7546. configurable: true
  7547. });
  7548. Object.defineProperty(Engine, "INCR_WRAP", {
  7549. get: function () {
  7550. return Engine._INCR_WRAP;
  7551. },
  7552. enumerable: true,
  7553. configurable: true
  7554. });
  7555. Object.defineProperty(Engine, "DECR_WRAP", {
  7556. get: function () {
  7557. return Engine._DECR_WRAP;
  7558. },
  7559. enumerable: true,
  7560. configurable: true
  7561. });
  7562. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  7563. get: function () {
  7564. return Engine._ALPHA_DISABLE;
  7565. },
  7566. enumerable: true,
  7567. configurable: true
  7568. });
  7569. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  7570. get: function () {
  7571. return Engine._ALPHA_ONEONE;
  7572. },
  7573. enumerable: true,
  7574. configurable: true
  7575. });
  7576. Object.defineProperty(Engine, "ALPHA_ADD", {
  7577. get: function () {
  7578. return Engine._ALPHA_ADD;
  7579. },
  7580. enumerable: true,
  7581. configurable: true
  7582. });
  7583. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  7584. get: function () {
  7585. return Engine._ALPHA_COMBINE;
  7586. },
  7587. enumerable: true,
  7588. configurable: true
  7589. });
  7590. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  7591. get: function () {
  7592. return Engine._ALPHA_SUBTRACT;
  7593. },
  7594. enumerable: true,
  7595. configurable: true
  7596. });
  7597. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  7598. get: function () {
  7599. return Engine._ALPHA_MULTIPLY;
  7600. },
  7601. enumerable: true,
  7602. configurable: true
  7603. });
  7604. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  7605. get: function () {
  7606. return Engine._ALPHA_MAXIMIZED;
  7607. },
  7608. enumerable: true,
  7609. configurable: true
  7610. });
  7611. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  7612. get: function () {
  7613. return Engine._ALPHA_PREMULTIPLIED;
  7614. },
  7615. enumerable: true,
  7616. configurable: true
  7617. });
  7618. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  7619. get: function () {
  7620. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  7621. },
  7622. enumerable: true,
  7623. configurable: true
  7624. });
  7625. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  7626. get: function () {
  7627. return Engine._ALPHA_INTERPOLATE;
  7628. },
  7629. enumerable: true,
  7630. configurable: true
  7631. });
  7632. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  7633. get: function () {
  7634. return Engine._ALPHA_SCREENMODE;
  7635. },
  7636. enumerable: true,
  7637. configurable: true
  7638. });
  7639. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  7640. get: function () {
  7641. return Engine._DELAYLOADSTATE_NONE;
  7642. },
  7643. enumerable: true,
  7644. configurable: true
  7645. });
  7646. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  7647. get: function () {
  7648. return Engine._DELAYLOADSTATE_LOADED;
  7649. },
  7650. enumerable: true,
  7651. configurable: true
  7652. });
  7653. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  7654. get: function () {
  7655. return Engine._DELAYLOADSTATE_LOADING;
  7656. },
  7657. enumerable: true,
  7658. configurable: true
  7659. });
  7660. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  7661. get: function () {
  7662. return Engine._DELAYLOADSTATE_NOTLOADED;
  7663. },
  7664. enumerable: true,
  7665. configurable: true
  7666. });
  7667. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  7668. get: function () {
  7669. return Engine._TEXTUREFORMAT_ALPHA;
  7670. },
  7671. enumerable: true,
  7672. configurable: true
  7673. });
  7674. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  7675. get: function () {
  7676. return Engine._TEXTUREFORMAT_LUMINANCE;
  7677. },
  7678. enumerable: true,
  7679. configurable: true
  7680. });
  7681. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  7682. get: function () {
  7683. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  7684. },
  7685. enumerable: true,
  7686. configurable: true
  7687. });
  7688. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  7689. get: function () {
  7690. return Engine._TEXTUREFORMAT_RGB;
  7691. },
  7692. enumerable: true,
  7693. configurable: true
  7694. });
  7695. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  7696. get: function () {
  7697. return Engine._TEXTUREFORMAT_RGBA;
  7698. },
  7699. enumerable: true,
  7700. configurable: true
  7701. });
  7702. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  7703. get: function () {
  7704. return Engine._TEXTURETYPE_UNSIGNED_INT;
  7705. },
  7706. enumerable: true,
  7707. configurable: true
  7708. });
  7709. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  7710. get: function () {
  7711. return Engine._TEXTURETYPE_FLOAT;
  7712. },
  7713. enumerable: true,
  7714. configurable: true
  7715. });
  7716. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  7717. get: function () {
  7718. return Engine._TEXTURETYPE_HALF_FLOAT;
  7719. },
  7720. enumerable: true,
  7721. configurable: true
  7722. });
  7723. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  7724. get: function () {
  7725. return Engine._SCALEMODE_FLOOR;
  7726. },
  7727. enumerable: true,
  7728. configurable: true
  7729. });
  7730. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  7731. get: function () {
  7732. return Engine._SCALEMODE_NEAREST;
  7733. },
  7734. enumerable: true,
  7735. configurable: true
  7736. });
  7737. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  7738. get: function () {
  7739. return Engine._SCALEMODE_CEILING;
  7740. },
  7741. enumerable: true,
  7742. configurable: true
  7743. });
  7744. Object.defineProperty(Engine, "Version", {
  7745. get: function () {
  7746. return "3.0-beta";
  7747. },
  7748. enumerable: true,
  7749. configurable: true
  7750. });
  7751. Object.defineProperty(Engine.prototype, "texturesSupported", {
  7752. get: function () {
  7753. return this._texturesSupported;
  7754. },
  7755. enumerable: true,
  7756. configurable: true
  7757. });
  7758. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  7759. get: function () {
  7760. return this._textureFormatInUse;
  7761. },
  7762. enumerable: true,
  7763. configurable: true
  7764. });
  7765. Object.defineProperty(Engine.prototype, "emptyTexture", {
  7766. // Empty texture
  7767. get: function () {
  7768. if (!this._emptyTexture) {
  7769. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7770. }
  7771. return this._emptyTexture;
  7772. },
  7773. enumerable: true,
  7774. configurable: true
  7775. });
  7776. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  7777. get: function () {
  7778. if (!this._emptyCubeTexture) {
  7779. var faceData = new Uint8Array(4);
  7780. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  7781. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7782. }
  7783. return this._emptyCubeTexture;
  7784. },
  7785. enumerable: true,
  7786. configurable: true
  7787. });
  7788. Object.defineProperty(Engine.prototype, "webGLVersion", {
  7789. get: function () {
  7790. return this._webGLVersion;
  7791. },
  7792. enumerable: true,
  7793. configurable: true
  7794. });
  7795. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  7796. /**
  7797. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  7798. */
  7799. get: function () {
  7800. return this._isStencilEnable;
  7801. },
  7802. enumerable: true,
  7803. configurable: true
  7804. });
  7805. Engine.prototype._prepareWorkingCanvas = function () {
  7806. if (this._workingCanvas) {
  7807. return;
  7808. }
  7809. this._workingCanvas = document.createElement("canvas");
  7810. this._workingContext = this._workingCanvas.getContext("2d");
  7811. };
  7812. Engine.prototype.resetTextureCache = function () {
  7813. for (var index = 0; index < this._maxTextureChannels; index++) {
  7814. this._activeTexturesCache[index] = null;
  7815. }
  7816. };
  7817. Engine.prototype.getGlInfo = function () {
  7818. return {
  7819. vendor: this._glVendor,
  7820. renderer: this._glRenderer,
  7821. version: this._glVersion
  7822. };
  7823. };
  7824. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  7825. if (useScreen === void 0) { useScreen = false; }
  7826. var viewport = camera.viewport;
  7827. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  7828. };
  7829. Engine.prototype.getRenderWidth = function (useScreen) {
  7830. if (useScreen === void 0) { useScreen = false; }
  7831. if (!useScreen && this._currentRenderTarget) {
  7832. return this._currentRenderTarget._width;
  7833. }
  7834. return this._renderingCanvas.width;
  7835. };
  7836. Engine.prototype.getRenderHeight = function (useScreen) {
  7837. if (useScreen === void 0) { useScreen = false; }
  7838. if (!useScreen && this._currentRenderTarget) {
  7839. return this._currentRenderTarget._height;
  7840. }
  7841. return this._renderingCanvas.height;
  7842. };
  7843. Engine.prototype.getRenderingCanvas = function () {
  7844. return this._renderingCanvas;
  7845. };
  7846. Engine.prototype.getRenderingCanvasClientRect = function () {
  7847. return this._renderingCanvas.getBoundingClientRect();
  7848. };
  7849. Engine.prototype.setHardwareScalingLevel = function (level) {
  7850. this._hardwareScalingLevel = level;
  7851. this.resize();
  7852. };
  7853. Engine.prototype.getHardwareScalingLevel = function () {
  7854. return this._hardwareScalingLevel;
  7855. };
  7856. Engine.prototype.getLoadedTexturesCache = function () {
  7857. return this._loadedTexturesCache;
  7858. };
  7859. Engine.prototype.getCaps = function () {
  7860. return this._caps;
  7861. };
  7862. Object.defineProperty(Engine.prototype, "drawCalls", {
  7863. get: function () {
  7864. return this._drawCalls.current;
  7865. },
  7866. enumerable: true,
  7867. configurable: true
  7868. });
  7869. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  7870. get: function () {
  7871. return this._drawCalls;
  7872. },
  7873. enumerable: true,
  7874. configurable: true
  7875. });
  7876. Engine.prototype.getDepthFunction = function () {
  7877. return this._depthCullingState.depthFunc;
  7878. };
  7879. Engine.prototype.setDepthFunction = function (depthFunc) {
  7880. this._depthCullingState.depthFunc = depthFunc;
  7881. };
  7882. Engine.prototype.setDepthFunctionToGreater = function () {
  7883. this._depthCullingState.depthFunc = this._gl.GREATER;
  7884. };
  7885. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  7886. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  7887. };
  7888. Engine.prototype.setDepthFunctionToLess = function () {
  7889. this._depthCullingState.depthFunc = this._gl.LESS;
  7890. };
  7891. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  7892. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  7893. };
  7894. Engine.prototype.getStencilBuffer = function () {
  7895. return this._stencilState.stencilTest;
  7896. };
  7897. Engine.prototype.setStencilBuffer = function (enable) {
  7898. this._stencilState.stencilTest = enable;
  7899. };
  7900. Engine.prototype.getStencilMask = function () {
  7901. return this._stencilState.stencilMask;
  7902. };
  7903. Engine.prototype.setStencilMask = function (mask) {
  7904. this._stencilState.stencilMask = mask;
  7905. };
  7906. Engine.prototype.getStencilFunction = function () {
  7907. return this._stencilState.stencilFunc;
  7908. };
  7909. Engine.prototype.getStencilFunctionReference = function () {
  7910. return this._stencilState.stencilFuncRef;
  7911. };
  7912. Engine.prototype.getStencilFunctionMask = function () {
  7913. return this._stencilState.stencilFuncMask;
  7914. };
  7915. Engine.prototype.setStencilFunction = function (stencilFunc) {
  7916. this._stencilState.stencilFunc = stencilFunc;
  7917. };
  7918. Engine.prototype.setStencilFunctionReference = function (reference) {
  7919. this._stencilState.stencilFuncRef = reference;
  7920. };
  7921. Engine.prototype.setStencilFunctionMask = function (mask) {
  7922. this._stencilState.stencilFuncMask = mask;
  7923. };
  7924. Engine.prototype.getStencilOperationFail = function () {
  7925. return this._stencilState.stencilOpStencilFail;
  7926. };
  7927. Engine.prototype.getStencilOperationDepthFail = function () {
  7928. return this._stencilState.stencilOpDepthFail;
  7929. };
  7930. Engine.prototype.getStencilOperationPass = function () {
  7931. return this._stencilState.stencilOpStencilDepthPass;
  7932. };
  7933. Engine.prototype.setStencilOperationFail = function (operation) {
  7934. this._stencilState.stencilOpStencilFail = operation;
  7935. };
  7936. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  7937. this._stencilState.stencilOpDepthFail = operation;
  7938. };
  7939. Engine.prototype.setStencilOperationPass = function (operation) {
  7940. this._stencilState.stencilOpStencilDepthPass = operation;
  7941. };
  7942. Engine.prototype.setDitheringState = function (value) {
  7943. if (value) {
  7944. this._gl.enable(this._gl.DITHER);
  7945. }
  7946. else {
  7947. this._gl.disable(this._gl.DITHER);
  7948. }
  7949. };
  7950. /**
  7951. * stop executing a render loop function and remove it from the execution array
  7952. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  7953. */
  7954. Engine.prototype.stopRenderLoop = function (renderFunction) {
  7955. if (!renderFunction) {
  7956. this._activeRenderLoops = [];
  7957. return;
  7958. }
  7959. var index = this._activeRenderLoops.indexOf(renderFunction);
  7960. if (index >= 0) {
  7961. this._activeRenderLoops.splice(index, 1);
  7962. }
  7963. };
  7964. Engine.prototype._renderLoop = function () {
  7965. var shouldRender = true;
  7966. if (!this.renderEvenInBackground && this._windowIsBackground) {
  7967. shouldRender = false;
  7968. }
  7969. if (shouldRender) {
  7970. // Start new frame
  7971. this.beginFrame();
  7972. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  7973. var renderFunction = this._activeRenderLoops[index];
  7974. renderFunction();
  7975. }
  7976. // Present
  7977. this.endFrame();
  7978. }
  7979. if (this._activeRenderLoops.length > 0) {
  7980. // Register new frame
  7981. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  7982. }
  7983. else {
  7984. this._renderingQueueLaunched = false;
  7985. }
  7986. };
  7987. /**
  7988. * Register and execute a render loop. The engine can have more than one render function.
  7989. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  7990. * @example
  7991. * engine.runRenderLoop(function () {
  7992. * scene.render()
  7993. * })
  7994. */
  7995. Engine.prototype.runRenderLoop = function (renderFunction) {
  7996. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  7997. return;
  7998. }
  7999. this._activeRenderLoops.push(renderFunction);
  8000. if (!this._renderingQueueLaunched) {
  8001. this._renderingQueueLaunched = true;
  8002. this._bindedRenderFunction = this._renderLoop.bind(this);
  8003. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8004. }
  8005. };
  8006. /**
  8007. * Toggle full screen mode.
  8008. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8009. * @param {any} options - an options object to be sent to the requestFullscreen function
  8010. */
  8011. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8012. if (this.isFullscreen) {
  8013. BABYLON.Tools.ExitFullscreen();
  8014. }
  8015. else {
  8016. this._pointerLockRequested = requestPointerLock;
  8017. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8018. }
  8019. };
  8020. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8021. if (stencil === void 0) { stencil = false; }
  8022. this.applyStates();
  8023. var mode = 0;
  8024. if (backBuffer && color) {
  8025. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8026. mode |= this._gl.COLOR_BUFFER_BIT;
  8027. }
  8028. if (depth) {
  8029. this._gl.clearDepth(1.0);
  8030. mode |= this._gl.DEPTH_BUFFER_BIT;
  8031. }
  8032. if (stencil) {
  8033. this._gl.clearStencil(0);
  8034. mode |= this._gl.STENCIL_BUFFER_BIT;
  8035. }
  8036. this._gl.clear(mode);
  8037. };
  8038. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8039. var gl = this._gl;
  8040. // Save state
  8041. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8042. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8043. // Change state
  8044. gl.enable(gl.SCISSOR_TEST);
  8045. gl.scissor(x, y, width, height);
  8046. // Clear
  8047. this.clear(clearColor, true, true, true);
  8048. // Restore state
  8049. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8050. if (curScissor === true) {
  8051. gl.enable(gl.SCISSOR_TEST);
  8052. }
  8053. else {
  8054. gl.disable(gl.SCISSOR_TEST);
  8055. }
  8056. };
  8057. /**
  8058. * Set the WebGL's viewport
  8059. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8060. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8061. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8062. */
  8063. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8064. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  8065. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  8066. var x = viewport.x || 0;
  8067. var y = viewport.y || 0;
  8068. this._cachedViewport = viewport;
  8069. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8070. };
  8071. /**
  8072. * Directly set the WebGL Viewport
  8073. * The x, y, width & height are directly passed to the WebGL call
  8074. * @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.
  8075. */
  8076. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8077. var currentViewport = this._cachedViewport;
  8078. this._cachedViewport = null;
  8079. this._gl.viewport(x, y, width, height);
  8080. return currentViewport;
  8081. };
  8082. Engine.prototype.beginFrame = function () {
  8083. this._measureFps();
  8084. };
  8085. Engine.prototype.endFrame = function () {
  8086. //force a flush in case we are using a bad OS.
  8087. if (this._badOS) {
  8088. this.flushFramebuffer();
  8089. }
  8090. //submit frame to the vr device, if enabled
  8091. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8092. this._vrDisplayEnabled.submitFrame();
  8093. }
  8094. };
  8095. /**
  8096. * resize the view according to the canvas' size.
  8097. * @example
  8098. * window.addEventListener("resize", function () {
  8099. * engine.resize();
  8100. * });
  8101. */
  8102. Engine.prototype.resize = function () {
  8103. // We're not resizing the size of the canvas while in VR mode & presenting
  8104. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8105. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8106. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8107. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8108. }
  8109. };
  8110. /**
  8111. * force a specific size of the canvas
  8112. * @param {number} width - the new canvas' width
  8113. * @param {number} height - the new canvas' height
  8114. */
  8115. Engine.prototype.setSize = function (width, height) {
  8116. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8117. return;
  8118. }
  8119. this._renderingCanvas.width = width;
  8120. this._renderingCanvas.height = height;
  8121. for (var index = 0; index < this.scenes.length; index++) {
  8122. var scene = this.scenes[index];
  8123. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8124. var cam = scene.cameras[camIndex];
  8125. cam._currentRenderId = 0;
  8126. }
  8127. }
  8128. if (this.onResizeObservable.hasObservers) {
  8129. this.onResizeObservable.notifyObservers(this);
  8130. }
  8131. };
  8132. //WebVR functions
  8133. Engine.prototype.isVRDevicePresent = function (callback) {
  8134. this.getVRDevice(null, function (device) {
  8135. callback(device !== null);
  8136. });
  8137. };
  8138. Engine.prototype.getVRDevice = function (name, callback) {
  8139. if (!this.vrDisplaysPromise) {
  8140. callback(null);
  8141. return;
  8142. }
  8143. this.vrDisplaysPromise.then(function (devices) {
  8144. if (devices.length > 0) {
  8145. if (name) {
  8146. var found = devices.some(function (device) {
  8147. if (device.displayName === name) {
  8148. callback(device);
  8149. return true;
  8150. }
  8151. else {
  8152. return false;
  8153. }
  8154. });
  8155. if (!found) {
  8156. BABYLON.Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  8157. callback(devices[0]);
  8158. }
  8159. }
  8160. else {
  8161. //choose the first one
  8162. callback(devices[0]);
  8163. }
  8164. }
  8165. else {
  8166. BABYLON.Tools.Error("No WebVR devices found!");
  8167. callback(null);
  8168. }
  8169. });
  8170. };
  8171. Engine.prototype.initWebVR = function () {
  8172. if (!this.vrDisplaysPromise) {
  8173. this._getVRDisplays();
  8174. }
  8175. };
  8176. Engine.prototype.enableVR = function (vrDevice) {
  8177. this._vrDisplayEnabled = vrDevice;
  8178. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8179. };
  8180. Engine.prototype.disableVR = function () {
  8181. if (this._vrDisplayEnabled) {
  8182. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8183. }
  8184. };
  8185. Engine.prototype._getVRDisplays = function () {
  8186. var _this = this;
  8187. var getWebVRDevices = function (devices) {
  8188. var size = devices.length;
  8189. var i = 0;
  8190. _this._vrDisplays = devices.filter(function (device) {
  8191. return devices[i] instanceof VRDisplay;
  8192. });
  8193. return _this._vrDisplays;
  8194. };
  8195. //using a key due to typescript
  8196. if (navigator.getVRDisplays) {
  8197. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8198. }
  8199. };
  8200. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  8201. this._currentRenderTarget = texture;
  8202. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8203. var gl = this._gl;
  8204. if (texture.isCube) {
  8205. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  8206. }
  8207. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  8208. this.wipeCaches();
  8209. };
  8210. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8211. if (this._currentFramebuffer !== framebuffer) {
  8212. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8213. this._currentFramebuffer = framebuffer;
  8214. }
  8215. };
  8216. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8217. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8218. this._currentRenderTarget = null;
  8219. // If MSAA, we need to bitblt back to main texture
  8220. var gl = this._gl;
  8221. if (texture._MSAAFramebuffer) {
  8222. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8223. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8224. gl.blitFramebuffer(0, 0, texture._width, texture._height, 0, 0, texture._width, texture._height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8225. }
  8226. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  8227. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8228. gl.generateMipmap(gl.TEXTURE_2D);
  8229. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8230. }
  8231. if (onBeforeUnbind) {
  8232. if (texture._MSAAFramebuffer) {
  8233. // Bind the correct framebuffer
  8234. this.bindUnboundFramebuffer(texture._framebuffer);
  8235. }
  8236. onBeforeUnbind();
  8237. }
  8238. this.bindUnboundFramebuffer(null);
  8239. };
  8240. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8241. if (texture.generateMipMaps) {
  8242. var gl = this._gl;
  8243. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8244. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8245. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8246. }
  8247. };
  8248. Engine.prototype.flushFramebuffer = function () {
  8249. this._gl.flush();
  8250. };
  8251. Engine.prototype.restoreDefaultFramebuffer = function () {
  8252. this._currentRenderTarget = null;
  8253. this.bindUnboundFramebuffer(null);
  8254. this.setViewport(this._cachedViewport);
  8255. this.wipeCaches();
  8256. };
  8257. // UBOs
  8258. Engine.prototype.createUniformBuffer = function (elements) {
  8259. var ubo = this._gl.createBuffer();
  8260. this.bindUniformBuffer(ubo);
  8261. if (elements instanceof Float32Array) {
  8262. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8263. }
  8264. else {
  8265. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8266. }
  8267. this.bindUniformBuffer(null);
  8268. ubo.references = 1;
  8269. return ubo;
  8270. };
  8271. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8272. var ubo = this._gl.createBuffer();
  8273. this.bindUniformBuffer(ubo);
  8274. if (elements instanceof Float32Array) {
  8275. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8276. }
  8277. else {
  8278. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8279. }
  8280. this.bindUniformBuffer(null);
  8281. ubo.references = 1;
  8282. return ubo;
  8283. };
  8284. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8285. this.bindUniformBuffer(uniformBuffer);
  8286. if (offset === undefined) {
  8287. offset = 0;
  8288. }
  8289. if (count === undefined) {
  8290. if (elements instanceof Float32Array) {
  8291. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8292. }
  8293. else {
  8294. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8295. }
  8296. }
  8297. else {
  8298. if (elements instanceof Float32Array) {
  8299. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8300. }
  8301. else {
  8302. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8303. }
  8304. }
  8305. this.bindUniformBuffer(null);
  8306. };
  8307. // VBOs
  8308. Engine.prototype._resetVertexBufferBinding = function () {
  8309. this.bindArrayBuffer(null);
  8310. this._cachedVertexBuffers = null;
  8311. };
  8312. Engine.prototype.createVertexBuffer = function (vertices) {
  8313. var vbo = this._gl.createBuffer();
  8314. this.bindArrayBuffer(vbo);
  8315. if (vertices instanceof Float32Array) {
  8316. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8317. }
  8318. else {
  8319. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8320. }
  8321. this._resetVertexBufferBinding();
  8322. vbo.references = 1;
  8323. return vbo;
  8324. };
  8325. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8326. var vbo = this._gl.createBuffer();
  8327. this.bindArrayBuffer(vbo);
  8328. if (vertices instanceof Float32Array) {
  8329. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8330. }
  8331. else {
  8332. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8333. }
  8334. this._resetVertexBufferBinding();
  8335. vbo.references = 1;
  8336. return vbo;
  8337. };
  8338. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8339. this.bindArrayBuffer(vertexBuffer);
  8340. if (offset === undefined) {
  8341. offset = 0;
  8342. }
  8343. if (count === undefined) {
  8344. if (vertices instanceof Float32Array) {
  8345. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8346. }
  8347. else {
  8348. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8349. }
  8350. }
  8351. else {
  8352. if (vertices instanceof Float32Array) {
  8353. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8354. }
  8355. else {
  8356. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8357. }
  8358. }
  8359. this._resetVertexBufferBinding();
  8360. };
  8361. Engine.prototype._resetIndexBufferBinding = function () {
  8362. this.bindIndexBuffer(null);
  8363. this._cachedIndexBuffer = null;
  8364. };
  8365. Engine.prototype.createIndexBuffer = function (indices) {
  8366. var vbo = this._gl.createBuffer();
  8367. this.bindIndexBuffer(vbo);
  8368. // Check for 32 bits indices
  8369. var arrayBuffer;
  8370. var need32Bits = false;
  8371. if (indices instanceof Uint16Array) {
  8372. arrayBuffer = indices;
  8373. }
  8374. else {
  8375. //check 32 bit support
  8376. if (this._caps.uintIndices) {
  8377. if (indices instanceof Uint32Array) {
  8378. arrayBuffer = indices;
  8379. need32Bits = true;
  8380. }
  8381. else {
  8382. //number[] or Int32Array, check if 32 bit is necessary
  8383. for (var index = 0; index < indices.length; index++) {
  8384. if (indices[index] > 65535) {
  8385. need32Bits = true;
  8386. break;
  8387. }
  8388. }
  8389. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8390. }
  8391. }
  8392. else {
  8393. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8394. arrayBuffer = new Uint16Array(indices);
  8395. }
  8396. }
  8397. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8398. this._resetIndexBufferBinding();
  8399. vbo.references = 1;
  8400. vbo.is32Bits = need32Bits;
  8401. return vbo;
  8402. };
  8403. Engine.prototype.bindArrayBuffer = function (buffer) {
  8404. if (!this._vaoRecordInProgress) {
  8405. this._unBindVertexArrayObject();
  8406. }
  8407. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8408. };
  8409. Engine.prototype.bindUniformBuffer = function (buffer) {
  8410. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  8411. };
  8412. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  8413. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  8414. };
  8415. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  8416. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  8417. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  8418. };
  8419. ;
  8420. Engine.prototype.bindIndexBuffer = function (buffer) {
  8421. if (!this._vaoRecordInProgress) {
  8422. this._unBindVertexArrayObject();
  8423. }
  8424. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8425. };
  8426. Engine.prototype.bindBuffer = function (buffer, target) {
  8427. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8428. this._gl.bindBuffer(target, buffer);
  8429. this._currentBoundBuffer[target] = buffer;
  8430. }
  8431. };
  8432. Engine.prototype.updateArrayBuffer = function (data) {
  8433. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8434. };
  8435. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8436. var pointer = this._currentBufferPointers[indx];
  8437. var changed = false;
  8438. if (!pointer) {
  8439. changed = true;
  8440. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  8441. }
  8442. else {
  8443. if (pointer.buffer !== buffer) {
  8444. pointer.buffer = buffer;
  8445. changed = true;
  8446. }
  8447. if (pointer.size !== size) {
  8448. pointer.size = size;
  8449. changed = true;
  8450. }
  8451. if (pointer.type !== type) {
  8452. pointer.type = type;
  8453. changed = true;
  8454. }
  8455. if (pointer.normalized !== normalized) {
  8456. pointer.normalized = normalized;
  8457. changed = true;
  8458. }
  8459. if (pointer.stride !== stride) {
  8460. pointer.stride = stride;
  8461. changed = true;
  8462. }
  8463. if (pointer.offset !== offset) {
  8464. pointer.offset = offset;
  8465. changed = true;
  8466. }
  8467. }
  8468. if (changed || this._vaoRecordInProgress) {
  8469. this.bindArrayBuffer(buffer);
  8470. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8471. }
  8472. };
  8473. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8474. if (indexBuffer == null) {
  8475. return;
  8476. }
  8477. if (this._cachedIndexBuffer !== indexBuffer) {
  8478. this._cachedIndexBuffer = indexBuffer;
  8479. this.bindIndexBuffer(indexBuffer);
  8480. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8481. }
  8482. };
  8483. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8484. var attributes = effect.getAttributesNames();
  8485. if (!this._vaoRecordInProgress) {
  8486. this._unBindVertexArrayObject();
  8487. }
  8488. this.unbindAllAttributes();
  8489. for (var index = 0; index < attributes.length; index++) {
  8490. var order = effect.getAttributeLocation(index);
  8491. if (order >= 0) {
  8492. var vertexBuffer = vertexBuffers[attributes[index]];
  8493. if (!vertexBuffer) {
  8494. continue;
  8495. }
  8496. this._gl.enableVertexAttribArray(order);
  8497. if (!this._vaoRecordInProgress) {
  8498. this._vertexAttribArraysEnabled[order] = true;
  8499. }
  8500. var buffer = vertexBuffer.getBuffer();
  8501. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8502. if (vertexBuffer.getIsInstanced()) {
  8503. this._gl.vertexAttribDivisor(order, 1);
  8504. if (!this._vaoRecordInProgress) {
  8505. this._currentInstanceLocations.push(order);
  8506. this._currentInstanceBuffers.push(buffer);
  8507. }
  8508. }
  8509. }
  8510. }
  8511. };
  8512. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8513. var vao = this._gl.createVertexArray();
  8514. this._vaoRecordInProgress = true;
  8515. this._gl.bindVertexArray(vao);
  8516. this._mustWipeVertexAttributes = true;
  8517. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8518. this.bindIndexBuffer(indexBuffer);
  8519. this._vaoRecordInProgress = false;
  8520. this._gl.bindVertexArray(null);
  8521. return vao;
  8522. };
  8523. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8524. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8525. this._cachedVertexArrayObject = vertexArrayObject;
  8526. this._gl.bindVertexArray(vertexArrayObject);
  8527. this._cachedVertexBuffers = null;
  8528. this._cachedIndexBuffer = null;
  8529. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8530. this._mustWipeVertexAttributes = true;
  8531. }
  8532. };
  8533. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  8534. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  8535. this._cachedVertexBuffers = vertexBuffer;
  8536. this._cachedEffectForVertexBuffers = effect;
  8537. var attributesCount = effect.getAttributesCount();
  8538. this._unBindVertexArrayObject();
  8539. this.unbindAllAttributes();
  8540. var offset = 0;
  8541. for (var index = 0; index < attributesCount; index++) {
  8542. if (index < vertexDeclaration.length) {
  8543. var order = effect.getAttributeLocation(index);
  8544. if (order >= 0) {
  8545. this._gl.enableVertexAttribArray(order);
  8546. this._vertexAttribArraysEnabled[order] = true;
  8547. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  8548. }
  8549. offset += vertexDeclaration[index] * 4;
  8550. }
  8551. }
  8552. }
  8553. this._bindIndexBufferWithCache(indexBuffer);
  8554. };
  8555. Engine.prototype._unBindVertexArrayObject = function () {
  8556. if (!this._cachedVertexArrayObject) {
  8557. return;
  8558. }
  8559. this._cachedVertexArrayObject = null;
  8560. this._gl.bindVertexArray(null);
  8561. };
  8562. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  8563. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  8564. this._cachedVertexBuffers = vertexBuffers;
  8565. this._cachedEffectForVertexBuffers = effect;
  8566. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8567. }
  8568. this._bindIndexBufferWithCache(indexBuffer);
  8569. };
  8570. Engine.prototype.unbindInstanceAttributes = function () {
  8571. var boundBuffer;
  8572. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  8573. var instancesBuffer = this._currentInstanceBuffers[i];
  8574. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  8575. boundBuffer = instancesBuffer;
  8576. this.bindArrayBuffer(instancesBuffer);
  8577. }
  8578. var offsetLocation = this._currentInstanceLocations[i];
  8579. this._gl.vertexAttribDivisor(offsetLocation, 0);
  8580. }
  8581. this._currentInstanceBuffers.length = 0;
  8582. this._currentInstanceLocations.length = 0;
  8583. };
  8584. Engine.prototype.releaseVertexArrayObject = function (vao) {
  8585. this._gl.deleteVertexArray(vao);
  8586. };
  8587. Engine.prototype._releaseBuffer = function (buffer) {
  8588. buffer.references--;
  8589. if (buffer.references === 0) {
  8590. this._gl.deleteBuffer(buffer);
  8591. return true;
  8592. }
  8593. return false;
  8594. };
  8595. Engine.prototype.createInstancesBuffer = function (capacity) {
  8596. var buffer = this._gl.createBuffer();
  8597. buffer.capacity = capacity;
  8598. this.bindArrayBuffer(buffer);
  8599. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  8600. return buffer;
  8601. };
  8602. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  8603. this._gl.deleteBuffer(buffer);
  8604. };
  8605. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  8606. this.bindArrayBuffer(instancesBuffer);
  8607. if (data) {
  8608. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8609. }
  8610. if (offsetLocations[0].index !== undefined) {
  8611. var stride = 0;
  8612. for (var i = 0; i < offsetLocations.length; i++) {
  8613. var ai = offsetLocations[i];
  8614. stride += ai.attributeSize * 4;
  8615. }
  8616. for (var i = 0; i < offsetLocations.length; i++) {
  8617. var ai = offsetLocations[i];
  8618. if (!this._vertexAttribArraysEnabled[ai.index]) {
  8619. this._gl.enableVertexAttribArray(ai.index);
  8620. this._vertexAttribArraysEnabled[ai.index] = true;
  8621. }
  8622. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  8623. this._gl.vertexAttribDivisor(ai.index, 1);
  8624. this._currentInstanceLocations.push(ai.index);
  8625. this._currentInstanceBuffers.push(instancesBuffer);
  8626. }
  8627. }
  8628. else {
  8629. for (var index = 0; index < 4; index++) {
  8630. var offsetLocation = offsetLocations[index];
  8631. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  8632. this._gl.enableVertexAttribArray(offsetLocation);
  8633. this._vertexAttribArraysEnabled[offsetLocation] = true;
  8634. }
  8635. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  8636. this._gl.vertexAttribDivisor(offsetLocation, 1);
  8637. this._currentInstanceLocations.push(offsetLocation);
  8638. this._currentInstanceBuffers.push(instancesBuffer);
  8639. }
  8640. }
  8641. };
  8642. Engine.prototype.applyStates = function () {
  8643. this._depthCullingState.apply(this._gl);
  8644. this._stencilState.apply(this._gl);
  8645. this._alphaState.apply(this._gl);
  8646. };
  8647. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  8648. // Apply states
  8649. this.applyStates();
  8650. this._drawCalls.addCount(1, false);
  8651. // Render
  8652. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  8653. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  8654. if (instancesCount) {
  8655. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  8656. return;
  8657. }
  8658. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  8659. };
  8660. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  8661. // Apply states
  8662. this.applyStates();
  8663. this._drawCalls.addCount(1, false);
  8664. if (instancesCount) {
  8665. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  8666. return;
  8667. }
  8668. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  8669. };
  8670. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  8671. // Apply states
  8672. this.applyStates();
  8673. this._drawCalls.addCount(1, false);
  8674. if (instancesCount) {
  8675. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  8676. return;
  8677. }
  8678. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  8679. };
  8680. // Shaders
  8681. Engine.prototype._releaseEffect = function (effect) {
  8682. if (this._compiledEffects[effect._key]) {
  8683. delete this._compiledEffects[effect._key];
  8684. if (effect.getProgram()) {
  8685. this._gl.deleteProgram(effect.getProgram());
  8686. }
  8687. }
  8688. };
  8689. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  8690. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  8691. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  8692. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  8693. if (this._compiledEffects[name]) {
  8694. return this._compiledEffects[name];
  8695. }
  8696. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  8697. effect._key = name;
  8698. this._compiledEffects[name] = effect;
  8699. return effect;
  8700. };
  8701. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  8702. if (uniformsNames === void 0) { uniformsNames = []; }
  8703. if (samplers === void 0) { samplers = []; }
  8704. if (defines === void 0) { defines = ""; }
  8705. return this.createEffect({
  8706. vertex: "particles",
  8707. fragmentElement: fragmentName
  8708. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  8709. };
  8710. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  8711. context = context || this._gl;
  8712. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  8713. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  8714. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  8715. var shaderProgram = context.createProgram();
  8716. context.attachShader(shaderProgram, vertexShader);
  8717. context.attachShader(shaderProgram, fragmentShader);
  8718. context.linkProgram(shaderProgram);
  8719. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  8720. if (!linked) {
  8721. var error = context.getProgramInfoLog(shaderProgram);
  8722. if (error) {
  8723. throw new Error(error);
  8724. }
  8725. }
  8726. context.deleteShader(vertexShader);
  8727. context.deleteShader(fragmentShader);
  8728. return shaderProgram;
  8729. };
  8730. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  8731. var results = [];
  8732. for (var index = 0; index < uniformsNames.length; index++) {
  8733. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  8734. }
  8735. return results;
  8736. };
  8737. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  8738. var results = [];
  8739. for (var index = 0; index < attributesNames.length; index++) {
  8740. try {
  8741. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  8742. }
  8743. catch (e) {
  8744. results.push(-1);
  8745. }
  8746. }
  8747. return results;
  8748. };
  8749. Engine.prototype.enableEffect = function (effect) {
  8750. // Use program
  8751. this.setProgram(effect.getProgram());
  8752. this._currentEffect = effect;
  8753. if (effect.onBind) {
  8754. effect.onBind(effect);
  8755. }
  8756. };
  8757. Engine.prototype.setIntArray = function (uniform, array) {
  8758. if (!uniform)
  8759. return;
  8760. this._gl.uniform1iv(uniform, array);
  8761. };
  8762. Engine.prototype.setIntArray2 = function (uniform, array) {
  8763. if (!uniform || array.length % 2 !== 0)
  8764. return;
  8765. this._gl.uniform2iv(uniform, array);
  8766. };
  8767. Engine.prototype.setIntArray3 = function (uniform, array) {
  8768. if (!uniform || array.length % 3 !== 0)
  8769. return;
  8770. this._gl.uniform3iv(uniform, array);
  8771. };
  8772. Engine.prototype.setIntArray4 = function (uniform, array) {
  8773. if (!uniform || array.length % 4 !== 0)
  8774. return;
  8775. this._gl.uniform4iv(uniform, array);
  8776. };
  8777. Engine.prototype.setFloatArray = function (uniform, array) {
  8778. if (!uniform)
  8779. return;
  8780. this._gl.uniform1fv(uniform, array);
  8781. };
  8782. Engine.prototype.setFloatArray2 = function (uniform, array) {
  8783. if (!uniform || array.length % 2 !== 0)
  8784. return;
  8785. this._gl.uniform2fv(uniform, array);
  8786. };
  8787. Engine.prototype.setFloatArray3 = function (uniform, array) {
  8788. if (!uniform || array.length % 3 !== 0)
  8789. return;
  8790. this._gl.uniform3fv(uniform, array);
  8791. };
  8792. Engine.prototype.setFloatArray4 = function (uniform, array) {
  8793. if (!uniform || array.length % 4 !== 0)
  8794. return;
  8795. this._gl.uniform4fv(uniform, array);
  8796. };
  8797. Engine.prototype.setArray = function (uniform, array) {
  8798. if (!uniform)
  8799. return;
  8800. this._gl.uniform1fv(uniform, array);
  8801. };
  8802. Engine.prototype.setArray2 = function (uniform, array) {
  8803. if (!uniform || array.length % 2 !== 0)
  8804. return;
  8805. this._gl.uniform2fv(uniform, array);
  8806. };
  8807. Engine.prototype.setArray3 = function (uniform, array) {
  8808. if (!uniform || array.length % 3 !== 0)
  8809. return;
  8810. this._gl.uniform3fv(uniform, array);
  8811. };
  8812. Engine.prototype.setArray4 = function (uniform, array) {
  8813. if (!uniform || array.length % 4 !== 0)
  8814. return;
  8815. this._gl.uniform4fv(uniform, array);
  8816. };
  8817. Engine.prototype.setMatrices = function (uniform, matrices) {
  8818. if (!uniform)
  8819. return;
  8820. this._gl.uniformMatrix4fv(uniform, false, matrices);
  8821. };
  8822. Engine.prototype.setMatrix = function (uniform, matrix) {
  8823. if (!uniform)
  8824. return;
  8825. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  8826. };
  8827. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  8828. if (!uniform)
  8829. return;
  8830. this._gl.uniformMatrix3fv(uniform, false, matrix);
  8831. };
  8832. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  8833. if (!uniform)
  8834. return;
  8835. this._gl.uniformMatrix2fv(uniform, false, matrix);
  8836. };
  8837. Engine.prototype.setFloat = function (uniform, value) {
  8838. if (!uniform)
  8839. return;
  8840. this._gl.uniform1f(uniform, value);
  8841. };
  8842. Engine.prototype.setFloat2 = function (uniform, x, y) {
  8843. if (!uniform)
  8844. return;
  8845. this._gl.uniform2f(uniform, x, y);
  8846. };
  8847. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  8848. if (!uniform)
  8849. return;
  8850. this._gl.uniform3f(uniform, x, y, z);
  8851. };
  8852. Engine.prototype.setBool = function (uniform, bool) {
  8853. if (!uniform)
  8854. return;
  8855. this._gl.uniform1i(uniform, bool);
  8856. };
  8857. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  8858. if (!uniform)
  8859. return;
  8860. this._gl.uniform4f(uniform, x, y, z, w);
  8861. };
  8862. Engine.prototype.setColor3 = function (uniform, color3) {
  8863. if (!uniform)
  8864. return;
  8865. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  8866. };
  8867. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  8868. if (!uniform)
  8869. return;
  8870. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  8871. };
  8872. // States
  8873. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  8874. if (zOffset === void 0) { zOffset = 0; }
  8875. if (reverseSide === void 0) { reverseSide = false; }
  8876. // Culling
  8877. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  8878. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  8879. var cullFace = this.cullBackFaces ? showSide : hideSide;
  8880. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  8881. if (culling) {
  8882. this._depthCullingState.cullFace = cullFace;
  8883. this._depthCullingState.cull = true;
  8884. }
  8885. else {
  8886. this._depthCullingState.cull = false;
  8887. }
  8888. }
  8889. // Z offset
  8890. this._depthCullingState.zOffset = zOffset;
  8891. };
  8892. Engine.prototype.setDepthBuffer = function (enable) {
  8893. this._depthCullingState.depthTest = enable;
  8894. };
  8895. Engine.prototype.getDepthWrite = function () {
  8896. return this._depthCullingState.depthMask;
  8897. };
  8898. Engine.prototype.setDepthWrite = function (enable) {
  8899. this._depthCullingState.depthMask = enable;
  8900. };
  8901. Engine.prototype.setColorWrite = function (enable) {
  8902. this._gl.colorMask(enable, enable, enable, enable);
  8903. };
  8904. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  8905. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  8906. };
  8907. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  8908. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  8909. if (this._alphaMode === mode) {
  8910. return;
  8911. }
  8912. switch (mode) {
  8913. case Engine.ALPHA_DISABLE:
  8914. this._alphaState.alphaBlend = false;
  8915. break;
  8916. case Engine.ALPHA_PREMULTIPLIED:
  8917. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8918. this._alphaState.alphaBlend = true;
  8919. break;
  8920. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  8921. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  8922. this._alphaState.alphaBlend = true;
  8923. break;
  8924. case Engine.ALPHA_COMBINE:
  8925. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8926. this._alphaState.alphaBlend = true;
  8927. break;
  8928. case Engine.ALPHA_ONEONE:
  8929. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8930. this._alphaState.alphaBlend = true;
  8931. break;
  8932. case Engine.ALPHA_ADD:
  8933. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8934. this._alphaState.alphaBlend = true;
  8935. break;
  8936. case Engine.ALPHA_SUBTRACT:
  8937. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8938. this._alphaState.alphaBlend = true;
  8939. break;
  8940. case Engine.ALPHA_MULTIPLY:
  8941. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  8942. this._alphaState.alphaBlend = true;
  8943. break;
  8944. case Engine.ALPHA_MAXIMIZED:
  8945. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8946. this._alphaState.alphaBlend = true;
  8947. break;
  8948. case Engine.ALPHA_INTERPOLATE:
  8949. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  8950. this._alphaState.alphaBlend = true;
  8951. break;
  8952. case Engine.ALPHA_SCREENMODE:
  8953. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  8954. this._alphaState.alphaBlend = true;
  8955. break;
  8956. }
  8957. if (!noDepthWriteChange) {
  8958. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  8959. }
  8960. this._alphaMode = mode;
  8961. };
  8962. Engine.prototype.getAlphaMode = function () {
  8963. return this._alphaMode;
  8964. };
  8965. Engine.prototype.setAlphaTesting = function (enable) {
  8966. this._alphaTest = enable;
  8967. };
  8968. Engine.prototype.getAlphaTesting = function () {
  8969. return !!this._alphaTest;
  8970. };
  8971. // Textures
  8972. Engine.prototype.wipeCaches = function (bruteForce) {
  8973. if (this.preventCacheWipeBetweenFrames) {
  8974. return;
  8975. }
  8976. this.resetTextureCache();
  8977. this._currentEffect = null;
  8978. // 6/8/2017: deltakosh: Should not be required anymore.
  8979. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  8980. if (bruteForce) {
  8981. this._stencilState.reset();
  8982. this._depthCullingState.reset();
  8983. this.setDepthFunctionToLessOrEqual();
  8984. this._alphaState.reset();
  8985. }
  8986. this._cachedVertexBuffers = null;
  8987. this._cachedIndexBuffer = null;
  8988. this._cachedEffectForVertexBuffers = null;
  8989. this._unBindVertexArrayObject();
  8990. this.bindIndexBuffer(null);
  8991. this.bindArrayBuffer(null);
  8992. };
  8993. /**
  8994. * Set the compressed texture format to use, based on the formats you have, and the formats
  8995. * supported by the hardware / browser.
  8996. *
  8997. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  8998. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  8999. * to API arguments needed to compressed textures. This puts the burden on the container
  9000. * generator to house the arcane code for determining these for current & future formats.
  9001. *
  9002. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9003. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9004. *
  9005. * Note: The result of this call is not taken into account when a texture is base64.
  9006. *
  9007. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9008. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9009. *
  9010. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9011. * @returns The extension selected.
  9012. */
  9013. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9014. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9015. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9016. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9017. return this._textureFormatInUse = this._texturesSupported[i];
  9018. }
  9019. }
  9020. }
  9021. // actively set format to nothing, to allow this to be called more than once
  9022. // and possibly fail the 2nd time
  9023. return this._textureFormatInUse = null;
  9024. };
  9025. /**
  9026. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9027. * @param {string} urlArg- This contains one of the following:
  9028. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9029. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9030. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9031. *
  9032. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9033. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9034. * @param {Scene} scene- Needed for loading to the correct scene.
  9035. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9036. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9037. * @param {callback} onError- Optional callback to be called upon failure.
  9038. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9039. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9040. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9041. *
  9042. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9043. */
  9044. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9045. var _this = this;
  9046. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9047. if (onLoad === void 0) { onLoad = null; }
  9048. if (onError === void 0) { onError = null; }
  9049. if (buffer === void 0) { buffer = null; }
  9050. var texture = fallBack ? fallBack : this._gl.createTexture();
  9051. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9052. var fromData = url.substr(0, 5) === "data:";
  9053. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9054. // establish the file extension, if possible
  9055. var lastDot = url.lastIndexOf('.');
  9056. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9057. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9058. if (isDDS) {
  9059. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  9060. }
  9061. var isTGA = (extension === ".tga");
  9062. // determine if a ktx file should be substituted
  9063. var isKTX = false;
  9064. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9065. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9066. isKTX = true;
  9067. }
  9068. scene._addPendingData(texture);
  9069. texture.url = url;
  9070. texture.noMipmap = noMipmap;
  9071. texture.references = 1;
  9072. texture.samplingMode = samplingMode;
  9073. texture.onLoadedCallbacks = [];
  9074. if (onLoad) {
  9075. texture.onLoadedCallbacks.push(onLoad);
  9076. }
  9077. if (!fallBack)
  9078. this._loadedTexturesCache.push(texture);
  9079. var onerror = function () {
  9080. scene._removePendingData(texture);
  9081. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9082. if (isKTX) {
  9083. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9084. }
  9085. else if (onError) {
  9086. onError();
  9087. }
  9088. };
  9089. var callback;
  9090. // processing for non-image formats
  9091. if (isKTX || isTGA || isDDS) {
  9092. if (isKTX) {
  9093. callback = function (data) {
  9094. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9095. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9096. ktx.uploadLevels(_this._gl, !noMipmap);
  9097. }, samplingMode);
  9098. };
  9099. }
  9100. else if (isTGA) {
  9101. callback = function (arrayBuffer) {
  9102. var data = new Uint8Array(arrayBuffer);
  9103. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9104. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9105. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9106. }, samplingMode);
  9107. };
  9108. }
  9109. else if (isDDS) {
  9110. callback = function (data) {
  9111. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9112. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9113. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9114. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  9115. }, samplingMode);
  9116. };
  9117. }
  9118. if (!buffer) {
  9119. BABYLON.Tools.LoadFile(url, function (data) {
  9120. callback(data);
  9121. }, null, scene.database, true, onerror);
  9122. }
  9123. else {
  9124. callback(buffer);
  9125. }
  9126. // image format processing
  9127. }
  9128. else {
  9129. var onload = function (img) {
  9130. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  9131. var isPot = (img.width === potWidth && img.height === potHeight);
  9132. if (!isPot) {
  9133. _this._prepareWorkingCanvas();
  9134. _this._workingCanvas.width = potWidth;
  9135. _this._workingCanvas.height = potHeight;
  9136. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9137. _this._workingContext.imageSmoothingEnabled = false;
  9138. _this._workingContext.mozImageSmoothingEnabled = false;
  9139. _this._workingContext.oImageSmoothingEnabled = false;
  9140. _this._workingContext.webkitImageSmoothingEnabled = false;
  9141. _this._workingContext.msImageSmoothingEnabled = false;
  9142. }
  9143. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  9144. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9145. _this._workingContext.imageSmoothingEnabled = true;
  9146. _this._workingContext.mozImageSmoothingEnabled = true;
  9147. _this._workingContext.oImageSmoothingEnabled = true;
  9148. _this._workingContext.webkitImageSmoothingEnabled = true;
  9149. _this._workingContext.msImageSmoothingEnabled = true;
  9150. }
  9151. }
  9152. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? _this._gl.RGB : _this._gl.RGBA);
  9153. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  9154. }, samplingMode);
  9155. };
  9156. if (!fromData || isBase64)
  9157. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  9158. else if (buffer instanceof Array || typeof buffer === "string")
  9159. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  9160. else
  9161. onload(buffer);
  9162. }
  9163. return texture;
  9164. };
  9165. Engine.prototype._getInternalFormat = function (format) {
  9166. var internalFormat = this._gl.RGBA;
  9167. switch (format) {
  9168. case Engine.TEXTUREFORMAT_ALPHA:
  9169. internalFormat = this._gl.ALPHA;
  9170. break;
  9171. case Engine.TEXTUREFORMAT_LUMINANCE:
  9172. internalFormat = this._gl.LUMINANCE;
  9173. break;
  9174. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9175. internalFormat = this._gl.LUMINANCE_ALPHA;
  9176. break;
  9177. case Engine.TEXTUREFORMAT_RGB:
  9178. internalFormat = this._gl.RGB;
  9179. break;
  9180. case Engine.TEXTUREFORMAT_RGBA:
  9181. internalFormat = this._gl.RGBA;
  9182. break;
  9183. }
  9184. return internalFormat;
  9185. };
  9186. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9187. if (compression === void 0) { compression = null; }
  9188. var internalFormat = this._getInternalFormat(format);
  9189. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9190. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9191. if (texture._width % 4 !== 0) {
  9192. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9193. }
  9194. if (compression) {
  9195. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  9196. }
  9197. else {
  9198. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9199. }
  9200. if (texture.generateMipMaps) {
  9201. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9202. }
  9203. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9204. this.resetTextureCache();
  9205. texture.isReady = true;
  9206. };
  9207. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9208. if (compression === void 0) { compression = null; }
  9209. var texture = this._gl.createTexture();
  9210. texture._baseWidth = width;
  9211. texture._baseHeight = height;
  9212. texture._width = width;
  9213. texture._height = height;
  9214. texture.references = 1;
  9215. this.updateRawTexture(texture, data, format, invertY, compression);
  9216. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9217. // Filters
  9218. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9219. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9220. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9221. if (generateMipMaps) {
  9222. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9223. }
  9224. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9225. texture.samplingMode = samplingMode;
  9226. this._loadedTexturesCache.push(texture);
  9227. return texture;
  9228. };
  9229. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9230. var texture = this._gl.createTexture();
  9231. texture._baseWidth = width;
  9232. texture._baseHeight = height;
  9233. if (generateMipMaps) {
  9234. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  9235. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  9236. }
  9237. this.resetTextureCache();
  9238. texture._width = width;
  9239. texture._height = height;
  9240. texture.isReady = false;
  9241. texture.generateMipMaps = generateMipMaps;
  9242. texture.references = 1;
  9243. texture.samplingMode = samplingMode;
  9244. this.updateTextureSamplingMode(samplingMode, texture);
  9245. this._loadedTexturesCache.push(texture);
  9246. return texture;
  9247. };
  9248. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9249. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9250. if (texture.isCube) {
  9251. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9252. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9253. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9254. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9255. }
  9256. else {
  9257. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9258. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9259. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9260. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9261. }
  9262. texture.samplingMode = samplingMode;
  9263. };
  9264. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9265. if (premulAlpha === void 0) { premulAlpha = false; }
  9266. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9267. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9268. if (premulAlpha) {
  9269. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9270. }
  9271. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9272. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9273. if (texture.generateMipMaps) {
  9274. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9275. }
  9276. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9277. if (premulAlpha) {
  9278. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9279. }
  9280. this.resetTextureCache();
  9281. texture.isReady = true;
  9282. };
  9283. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9284. if (texture._isDisabled) {
  9285. return;
  9286. }
  9287. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9288. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9289. try {
  9290. // Testing video texture support
  9291. if (this._videoTextureSupported === undefined) {
  9292. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9293. if (this._gl.getError() !== 0) {
  9294. this._videoTextureSupported = false;
  9295. }
  9296. else {
  9297. this._videoTextureSupported = true;
  9298. }
  9299. }
  9300. // Copy video through the current working canvas if video texture is not supported
  9301. if (!this._videoTextureSupported) {
  9302. if (!texture._workingCanvas) {
  9303. texture._workingCanvas = document.createElement("canvas");
  9304. texture._workingContext = texture._workingCanvas.getContext("2d");
  9305. texture._workingCanvas.width = texture._width;
  9306. texture._workingCanvas.height = texture._height;
  9307. }
  9308. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  9309. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9310. }
  9311. else {
  9312. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9313. }
  9314. if (texture.generateMipMaps) {
  9315. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9316. }
  9317. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9318. this.resetTextureCache();
  9319. texture.isReady = true;
  9320. }
  9321. catch (ex) {
  9322. // Something unexpected
  9323. // Let's disable the texture
  9324. texture._isDisabled = true;
  9325. }
  9326. };
  9327. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9328. // old version had a "generateMipMaps" arg instead of options.
  9329. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9330. // in the same way, generateDepthBuffer is defaulted to true
  9331. var generateMipMaps = false;
  9332. var generateDepthBuffer = true;
  9333. var generateStencilBuffer = false;
  9334. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9335. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9336. if (options !== undefined) {
  9337. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9338. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9339. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9340. type = options.type === undefined ? type : options.type;
  9341. if (options.samplingMode !== undefined) {
  9342. samplingMode = options.samplingMode;
  9343. }
  9344. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9345. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9346. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9347. }
  9348. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9349. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9350. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9351. }
  9352. }
  9353. var gl = this._gl;
  9354. var texture = gl.createTexture();
  9355. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9356. var width = size.width || size;
  9357. var height = size.height || size;
  9358. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9359. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9360. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9361. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9362. }
  9363. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9364. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9365. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9366. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9367. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9368. // Create the framebuffer
  9369. var framebuffer = gl.createFramebuffer();
  9370. this.bindUnboundFramebuffer(framebuffer);
  9371. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9372. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9373. if (generateMipMaps) {
  9374. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9375. }
  9376. // Unbind
  9377. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9378. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9379. this.bindUnboundFramebuffer(null);
  9380. texture._framebuffer = framebuffer;
  9381. texture._baseWidth = width;
  9382. texture._baseHeight = height;
  9383. texture._width = width;
  9384. texture._height = height;
  9385. texture.isReady = true;
  9386. texture.samples = 1;
  9387. texture.generateMipMaps = generateMipMaps;
  9388. texture.references = 1;
  9389. texture.samplingMode = samplingMode;
  9390. texture.type = type;
  9391. texture._generateDepthBuffer = generateDepthBuffer;
  9392. texture._generateStencilBuffer = generateStencilBuffer;
  9393. this.resetTextureCache();
  9394. this._loadedTexturesCache.push(texture);
  9395. return texture;
  9396. };
  9397. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  9398. var generateMipMaps = false;
  9399. var generateDepthBuffer = true;
  9400. var generateStencilBuffer = false;
  9401. var generateDepthTexture = false;
  9402. var textureCount = 1;
  9403. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  9404. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9405. var types = [], samplingModes = [];
  9406. if (options !== undefined) {
  9407. generateMipMaps = options.generateMipMaps;
  9408. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9409. generateStencilBuffer = options.generateStencilBuffer;
  9410. generateDepthTexture = options.generateDepthTexture;
  9411. textureCount = options.textureCount || 1;
  9412. if (options.types) {
  9413. types = options.types;
  9414. }
  9415. if (options.samplingModes) {
  9416. samplingModes = options.samplingModes;
  9417. }
  9418. }
  9419. var gl = this._gl;
  9420. // Create the framebuffer
  9421. var framebuffer = gl.createFramebuffer();
  9422. this.bindUnboundFramebuffer(framebuffer);
  9423. var colorRenderbuffer = gl.createRenderbuffer();
  9424. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9425. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, 4, gl.RGBA8, width, height);
  9426. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  9427. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9428. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT1, gl.RENDERBUFFER, colorRenderbuffer);
  9429. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, colorRenderbuffer);
  9430. var width = size.width || size;
  9431. var height = size.height || size;
  9432. var textures = [];
  9433. var attachments = [];
  9434. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9435. for (var i = 0; i < textureCount; i++) {
  9436. var samplingMode = samplingModes[i] || defaultSamplingMode;
  9437. var type = types[i] || defaultType;
  9438. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9439. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9440. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9441. }
  9442. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9443. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9444. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9445. }
  9446. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9447. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9448. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9449. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9450. }
  9451. var texture = gl.createTexture();
  9452. var attachment = gl["COLOR_ATTACHMENT" + i];
  9453. textures.push(texture);
  9454. attachments.push(attachment);
  9455. gl.activeTexture(gl["TEXTURE" + i]);
  9456. gl.bindTexture(gl.TEXTURE_2D, texture);
  9457. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9458. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9459. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9460. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9461. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9462. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture, 0);
  9463. if (generateMipMaps) {
  9464. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9465. }
  9466. // Unbind
  9467. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9468. texture._framebuffer = framebuffer;
  9469. texture._depthStencilBuffer = depthStencilBuffer;
  9470. texture._baseWidth = width;
  9471. texture._baseHeight = height;
  9472. texture._width = width;
  9473. texture._height = height;
  9474. texture.isReady = true;
  9475. texture.samples = 1;
  9476. texture.generateMipMaps = generateMipMaps;
  9477. texture.references = 1;
  9478. texture.samplingMode = samplingMode;
  9479. texture.type = type;
  9480. texture._generateDepthBuffer = generateDepthBuffer;
  9481. texture._generateStencilBuffer = generateStencilBuffer;
  9482. this._loadedTexturesCache.push(texture);
  9483. }
  9484. if (generateDepthTexture) {
  9485. // Depth texture
  9486. var depthTexture = gl.createTexture();
  9487. gl.activeTexture(gl.TEXTURE0);
  9488. gl.bindTexture(gl.TEXTURE_2D, depthTexture);
  9489. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9490. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9491. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9492. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9493. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  9494. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture, 0);
  9495. depthTexture._framebuffer = framebuffer;
  9496. depthTexture._baseWidth = width;
  9497. depthTexture._baseHeight = height;
  9498. depthTexture._width = width;
  9499. depthTexture._height = height;
  9500. depthTexture.isReady = true;
  9501. depthTexture.samples = 1;
  9502. depthTexture.generateMipMaps = generateMipMaps;
  9503. depthTexture.references = 1;
  9504. depthTexture.samplingMode = gl.NEAREST;
  9505. depthTexture._generateDepthBuffer = generateDepthBuffer;
  9506. depthTexture._generateStencilBuffer = generateStencilBuffer;
  9507. textures.push(depthTexture);
  9508. this._loadedTexturesCache.push(depthTexture);
  9509. }
  9510. gl.drawBuffers(attachments);
  9511. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9512. this.bindUnboundFramebuffer(null);
  9513. this.resetTextureCache();
  9514. return textures;
  9515. };
  9516. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  9517. if (samples === void 0) { samples = 1; }
  9518. var depthStencilBuffer = null;
  9519. var gl = this._gl;
  9520. // Create the depth/stencil buffer
  9521. if (generateStencilBuffer) {
  9522. depthStencilBuffer = gl.createRenderbuffer();
  9523. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9524. if (samples > 1) {
  9525. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_STENCIL, width, height);
  9526. }
  9527. else {
  9528. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9529. }
  9530. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9531. }
  9532. else if (generateDepthBuffer) {
  9533. depthStencilBuffer = gl.createRenderbuffer();
  9534. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9535. if (samples > 1) {
  9536. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  9537. }
  9538. else {
  9539. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9540. }
  9541. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9542. }
  9543. return depthStencilBuffer;
  9544. };
  9545. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  9546. if (this.webGLVersion < 2) {
  9547. return 1;
  9548. }
  9549. if (texture.samples === samples) {
  9550. return samples;
  9551. }
  9552. var gl = this._gl;
  9553. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  9554. // Dispose previous render buffers
  9555. if (texture._depthStencilBuffer) {
  9556. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9557. }
  9558. if (texture._MSAAFramebuffer) {
  9559. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9560. }
  9561. if (texture._MSAARenderBuffer) {
  9562. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9563. }
  9564. if (samples > 1) {
  9565. texture._MSAAFramebuffer = gl.createFramebuffer();
  9566. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  9567. var colorRenderbuffer = gl.createRenderbuffer();
  9568. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9569. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  9570. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9571. texture._MSAARenderBuffer = colorRenderbuffer;
  9572. }
  9573. else {
  9574. this.bindUnboundFramebuffer(texture._framebuffer);
  9575. }
  9576. texture.samples = samples;
  9577. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  9578. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9579. this.bindUnboundFramebuffer(null);
  9580. return samples;
  9581. };
  9582. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  9583. var gl = this._gl;
  9584. var texture = gl.createTexture();
  9585. var generateMipMaps = true;
  9586. var generateDepthBuffer = true;
  9587. var generateStencilBuffer = false;
  9588. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9589. if (options !== undefined) {
  9590. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9591. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9592. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9593. if (options.samplingMode !== undefined) {
  9594. samplingMode = options.samplingMode;
  9595. }
  9596. }
  9597. texture.isCube = true;
  9598. texture.references = 1;
  9599. texture.generateMipMaps = generateMipMaps;
  9600. texture.references = 1;
  9601. texture.samples = 1;
  9602. texture.samplingMode = samplingMode;
  9603. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9604. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9605. for (var face = 0; face < 6; face++) {
  9606. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  9607. }
  9608. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9609. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9610. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9611. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9612. // Create the framebuffer
  9613. var framebuffer = gl.createFramebuffer();
  9614. this.bindUnboundFramebuffer(framebuffer);
  9615. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  9616. // Mipmaps
  9617. if (texture.generateMipMaps) {
  9618. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9619. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9620. }
  9621. // Unbind
  9622. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9623. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9624. this.bindUnboundFramebuffer(null);
  9625. texture._framebuffer = framebuffer;
  9626. texture._width = size;
  9627. texture._height = size;
  9628. texture.isReady = true;
  9629. this.resetTextureCache();
  9630. this._loadedTexturesCache.push(texture);
  9631. return texture;
  9632. };
  9633. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format) {
  9634. var _this = this;
  9635. if (onLoad === void 0) { onLoad = null; }
  9636. if (onError === void 0) { onError = null; }
  9637. var gl = this._gl;
  9638. var texture = gl.createTexture();
  9639. texture.isCube = true;
  9640. texture.url = rootUrl;
  9641. texture.references = 1;
  9642. texture.onLoadedCallbacks = [];
  9643. var isKTX = false;
  9644. var lastDot = rootUrl.lastIndexOf('.');
  9645. var extension = rootUrl.substring(lastDot).toLowerCase();
  9646. if (this._textureFormatInUse) {
  9647. extension = this._textureFormatInUse;
  9648. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  9649. isKTX = true;
  9650. }
  9651. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9652. if (isDDS) {
  9653. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  9654. }
  9655. if (isKTX) {
  9656. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9657. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  9658. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  9659. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9660. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9661. ktx.uploadLevels(_this._gl, !noMipmap);
  9662. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9663. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9664. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9665. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9666. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9667. _this.resetTextureCache();
  9668. texture._width = ktx.pixelWidth;
  9669. texture._height = ktx.pixelHeight;
  9670. texture.isReady = true;
  9671. }, null, null, true, onError);
  9672. }
  9673. else if (isDDS) {
  9674. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9675. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9676. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  9677. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9678. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9679. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  9680. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  9681. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9682. }
  9683. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9684. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9685. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9686. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9687. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9688. _this.resetTextureCache();
  9689. texture._width = info.width;
  9690. texture._height = info.height;
  9691. texture.isReady = true;
  9692. }, null, null, true, onError);
  9693. }
  9694. else {
  9695. cascadeLoad(rootUrl, scene, function (imgs) {
  9696. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  9697. var height = width;
  9698. _this._prepareWorkingCanvas();
  9699. _this._workingCanvas.width = width;
  9700. _this._workingCanvas.height = height;
  9701. var faces = [
  9702. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9703. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9704. ];
  9705. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9706. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9707. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  9708. for (var index = 0; index < faces.length; index++) {
  9709. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  9710. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  9711. }
  9712. if (!noMipmap) {
  9713. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9714. }
  9715. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9716. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  9717. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9718. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9719. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9720. _this.resetTextureCache();
  9721. texture._width = width;
  9722. texture._height = height;
  9723. texture.isReady = true;
  9724. texture.onLoadedCallbacks.forEach(function (callback) {
  9725. callback();
  9726. });
  9727. if (onLoad) {
  9728. onLoad();
  9729. }
  9730. }, files, onError);
  9731. }
  9732. this._loadedTexturesCache.push(texture);
  9733. return texture;
  9734. };
  9735. Engine.prototype.updateTextureSize = function (texture, width, height) {
  9736. texture._width = width;
  9737. texture._height = height;
  9738. texture._size = width * height;
  9739. texture._baseWidth = width;
  9740. texture._baseHeight = height;
  9741. };
  9742. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  9743. if (compression === void 0) { compression = null; }
  9744. if (level === void 0) { level = 0; }
  9745. var gl = this._gl;
  9746. var textureType = this._getWebGLTextureType(type);
  9747. var internalFormat = this._getInternalFormat(format);
  9748. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9749. var needConversion = false;
  9750. if (internalFormat === gl.RGB) {
  9751. internalFormat = gl.RGBA;
  9752. needConversion = true;
  9753. }
  9754. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9755. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9756. if (texture._width % 4 !== 0) {
  9757. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  9758. }
  9759. var facesIndex = [
  9760. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9761. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9762. ];
  9763. // Data are known to be in +X +Y +Z -X -Y -Z
  9764. for (var index = 0; index < facesIndex.length; index++) {
  9765. var faceData = data[index];
  9766. if (compression) {
  9767. gl.compressedTexImage2D(facesIndex[index], level, this.getCaps().s3tc[compression], texture._width, texture._height, 0, faceData);
  9768. }
  9769. else {
  9770. if (needConversion) {
  9771. faceData = this._convertRGBtoRGBATextureData(faceData, texture._width, texture._height, type);
  9772. }
  9773. gl.texImage2D(facesIndex[index], level, internalSizedFomat, texture._width, texture._height, 0, internalFormat, textureType, faceData);
  9774. }
  9775. }
  9776. var isPot = (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  9777. if (isPot && texture.generateMipMaps && level === 0) {
  9778. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  9779. }
  9780. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9781. this.resetTextureCache();
  9782. texture.isReady = true;
  9783. };
  9784. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  9785. if (compression === void 0) { compression = null; }
  9786. var gl = this._gl;
  9787. var texture = gl.createTexture();
  9788. texture.isCube = true;
  9789. texture.references = 1;
  9790. var textureType = this._getWebGLTextureType(type);
  9791. var internalFormat = this._getInternalFormat(format);
  9792. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9793. var needConversion = false;
  9794. if (internalFormat === gl.RGB) {
  9795. internalFormat = gl.RGBA;
  9796. needConversion = true;
  9797. }
  9798. var width = size;
  9799. var height = width;
  9800. texture._width = width;
  9801. texture._height = height;
  9802. // Double check on POT to generate Mips.
  9803. var isPot = (BABYLON.Tools.IsExponentOfTwo(texture._width) && BABYLON.Tools.IsExponentOfTwo(texture._height));
  9804. if (!isPot) {
  9805. generateMipMaps = false;
  9806. }
  9807. texture.generateMipMaps = generateMipMaps;
  9808. // Upload data if needed. The texture won t be ready until then.
  9809. if (data) {
  9810. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  9811. }
  9812. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9813. // Filters
  9814. if (data && generateMipMaps) {
  9815. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  9816. }
  9817. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  9818. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9819. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9820. }
  9821. else if (textureType === Engine.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  9822. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9823. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9824. }
  9825. else {
  9826. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9827. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9828. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9829. }
  9830. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9831. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9832. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9833. this._loadedTexturesCache.push(texture);
  9834. return texture;
  9835. };
  9836. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  9837. var _this = this;
  9838. if (onLoad === void 0) { onLoad = null; }
  9839. if (onError === void 0) { onError = null; }
  9840. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9841. if (invertY === void 0) { invertY = false; }
  9842. var gl = this._gl;
  9843. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  9844. scene._addPendingData(texture);
  9845. texture.url = url;
  9846. var onerror = function () {
  9847. scene._removePendingData(texture);
  9848. if (onError) {
  9849. onError();
  9850. }
  9851. };
  9852. var internalCallback = function (data) {
  9853. var rgbeDataArrays = callback(data);
  9854. var facesIndex = [
  9855. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9856. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9857. ];
  9858. var width = texture._width;
  9859. var height = texture._height;
  9860. if (mipmmapGenerator) {
  9861. // TODO Remove this once Proper CubeMap Blur... This has nothing to do in engine...
  9862. // I ll remove ASAP.
  9863. var textureType = _this._getWebGLTextureType(type);
  9864. var internalFormat = _this._getInternalFormat(format);
  9865. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  9866. var needConversion = false;
  9867. if (internalFormat === gl.RGB) {
  9868. internalFormat = gl.RGBA;
  9869. needConversion = true;
  9870. }
  9871. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9872. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9873. var arrayTemp = [];
  9874. // Data are known to be in +X +Y +Z -X -Y -Z
  9875. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  9876. arrayTemp.push(rgbeDataArrays[0]); // +X
  9877. arrayTemp.push(rgbeDataArrays[3]); // -X
  9878. arrayTemp.push(rgbeDataArrays[1]); // +Y
  9879. arrayTemp.push(rgbeDataArrays[4]); // -Y
  9880. arrayTemp.push(rgbeDataArrays[2]); // +Z
  9881. arrayTemp.push(rgbeDataArrays[5]); // -Z
  9882. var mipData = mipmmapGenerator(arrayTemp);
  9883. // mipData is order in +X -X +Y -Y +Z -Z
  9884. var mipFaces = [0, 2, 4, 1, 3, 5];
  9885. for (var level = 0; level < mipData.length; level++) {
  9886. var mipSize = width >> level;
  9887. for (var mipIndex in mipFaces) {
  9888. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  9889. if (needConversion) {
  9890. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  9891. }
  9892. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  9893. }
  9894. }
  9895. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9896. }
  9897. else {
  9898. texture.generateMipMaps = !noMipmap;
  9899. _this.updateRawCubeTexture(texture, rgbeDataArrays, format, type, invertY);
  9900. }
  9901. texture.isReady = true;
  9902. _this.resetTextureCache();
  9903. scene._removePendingData(texture);
  9904. if (onLoad) {
  9905. onLoad();
  9906. }
  9907. };
  9908. BABYLON.Tools.LoadFile(url, function (data) {
  9909. internalCallback(data);
  9910. }, onerror, scene.database, true);
  9911. return texture;
  9912. };
  9913. ;
  9914. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  9915. // Create new RGBA data container.
  9916. var rgbaData;
  9917. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  9918. rgbaData = new Float32Array(width * height * 4);
  9919. }
  9920. else {
  9921. rgbaData = new Uint32Array(width * height * 4);
  9922. }
  9923. // Convert each pixel.
  9924. for (var x = 0; x < width; x++) {
  9925. for (var y = 0; y < height; y++) {
  9926. var index = (y * width + x) * 3;
  9927. var newIndex = (y * width + x) * 4;
  9928. // Map Old Value to new value.
  9929. rgbaData[newIndex + 0] = rgbData[index + 0];
  9930. rgbaData[newIndex + 1] = rgbData[index + 1];
  9931. rgbaData[newIndex + 2] = rgbData[index + 2];
  9932. // Add fully opaque alpha channel.
  9933. rgbaData[newIndex + 3] = 1;
  9934. }
  9935. }
  9936. return rgbaData;
  9937. };
  9938. Engine.prototype._releaseTexture = function (texture) {
  9939. var gl = this._gl;
  9940. if (texture._framebuffer) {
  9941. gl.deleteFramebuffer(texture._framebuffer);
  9942. }
  9943. if (texture._depthStencilBuffer) {
  9944. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9945. }
  9946. if (texture._MSAAFramebuffer) {
  9947. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9948. }
  9949. if (texture._MSAARenderBuffer) {
  9950. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9951. }
  9952. gl.deleteTexture(texture);
  9953. // Unbind channels
  9954. this.unbindAllTextures();
  9955. var index = this._loadedTexturesCache.indexOf(texture);
  9956. if (index !== -1) {
  9957. this._loadedTexturesCache.splice(index, 1);
  9958. }
  9959. };
  9960. Engine.prototype.setProgram = function (program) {
  9961. if (this._currentProgram !== program) {
  9962. this._gl.useProgram(program);
  9963. this._currentProgram = program;
  9964. }
  9965. };
  9966. Engine.prototype.bindSamplers = function (effect) {
  9967. this.setProgram(effect.getProgram());
  9968. var samplers = effect.getSamplers();
  9969. for (var index = 0; index < samplers.length; index++) {
  9970. var uniform = effect.getUniform(samplers[index]);
  9971. this._gl.uniform1i(uniform, index);
  9972. }
  9973. this._currentEffect = null;
  9974. };
  9975. Engine.prototype.activateTexture = function (texture) {
  9976. if (this._activeTexture !== texture) {
  9977. this._gl.activeTexture(texture);
  9978. this._activeTexture = texture;
  9979. }
  9980. };
  9981. Engine.prototype._bindTextureDirectly = function (target, texture) {
  9982. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  9983. this._gl.bindTexture(target, texture);
  9984. this._activeTexturesCache[this._activeTexture] = texture;
  9985. }
  9986. };
  9987. Engine.prototype._bindTexture = function (channel, texture) {
  9988. if (channel < 0) {
  9989. return;
  9990. }
  9991. this.activateTexture(this._gl.TEXTURE0 + channel);
  9992. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9993. };
  9994. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  9995. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  9996. };
  9997. Engine.prototype.unbindAllTextures = function () {
  9998. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  9999. this.activateTexture(this._gl["TEXTURE" + channel]);
  10000. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10001. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10002. }
  10003. };
  10004. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10005. if (channel < 0) {
  10006. return;
  10007. }
  10008. this._gl.uniform1i(uniform, channel);
  10009. this._setTexture(channel, texture);
  10010. };
  10011. Engine.prototype._setTexture = function (channel, texture) {
  10012. // Not ready?
  10013. if (!texture) {
  10014. if (this._activeTexturesCache[channel] != null) {
  10015. this.activateTexture(this._gl["TEXTURE" + channel]);
  10016. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10017. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10018. }
  10019. return;
  10020. }
  10021. // Video
  10022. var alreadyActivated = false;
  10023. if (texture.video) {
  10024. this.activateTexture(this._gl["TEXTURE" + channel]);
  10025. alreadyActivated = true;
  10026. texture.update();
  10027. }
  10028. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10029. texture.delayLoad();
  10030. return;
  10031. }
  10032. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  10033. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  10034. if (this._activeTexturesCache[channel] === internalTexture) {
  10035. return;
  10036. }
  10037. if (!alreadyActivated) {
  10038. this.activateTexture(this._gl["TEXTURE" + channel]);
  10039. }
  10040. if (internalTexture.isCube) {
  10041. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10042. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10043. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10044. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10045. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10046. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10047. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10048. }
  10049. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10050. }
  10051. else {
  10052. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10053. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10054. internalTexture._cachedWrapU = texture.wrapU;
  10055. switch (texture.wrapU) {
  10056. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10057. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10058. break;
  10059. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10060. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10061. break;
  10062. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10063. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10064. break;
  10065. }
  10066. }
  10067. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10068. internalTexture._cachedWrapV = texture.wrapV;
  10069. switch (texture.wrapV) {
  10070. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10071. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10072. break;
  10073. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10074. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10075. break;
  10076. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10077. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10078. break;
  10079. }
  10080. }
  10081. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10082. }
  10083. };
  10084. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10085. if (channel < 0) {
  10086. return;
  10087. }
  10088. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10089. this._textureUnits = new Int32Array(textures.length);
  10090. }
  10091. for (var i = 0; i < textures.length; i++) {
  10092. this._textureUnits[i] = channel + i;
  10093. }
  10094. this._gl.uniform1iv(uniform, this._textureUnits);
  10095. for (var index = 0; index < textures.length; index++) {
  10096. this._setTexture(channel + index, textures[index]);
  10097. }
  10098. };
  10099. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10100. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10101. var value = texture.anisotropicFilteringLevel;
  10102. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10103. value = 1;
  10104. }
  10105. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  10106. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10107. texture._cachedAnisotropicFilteringLevel = value;
  10108. }
  10109. };
  10110. Engine.prototype.readPixels = function (x, y, width, height) {
  10111. var data = new Uint8Array(height * width * 4);
  10112. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10113. return data;
  10114. };
  10115. /**
  10116. * Add an externaly attached data from its key.
  10117. * This method call will fail and return false, if such key already exists.
  10118. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10119. * @param key the unique key that identifies the data
  10120. * @param data the data object to associate to the key for this Engine instance
  10121. * @return true if no such key were already present and the data was added successfully, false otherwise
  10122. */
  10123. Engine.prototype.addExternalData = function (key, data) {
  10124. if (!this._externalData) {
  10125. this._externalData = new BABYLON.StringDictionary();
  10126. }
  10127. return this._externalData.add(key, data);
  10128. };
  10129. /**
  10130. * Get an externaly attached data from its key
  10131. * @param key the unique key that identifies the data
  10132. * @return the associated data, if present (can be null), or undefined if not present
  10133. */
  10134. Engine.prototype.getExternalData = function (key) {
  10135. if (!this._externalData) {
  10136. this._externalData = new BABYLON.StringDictionary();
  10137. }
  10138. return this._externalData.get(key);
  10139. };
  10140. /**
  10141. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10142. * @param key the unique key that identifies the data
  10143. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10144. * @return the associated data, can be null if the factory returned null.
  10145. */
  10146. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10147. if (!this._externalData) {
  10148. this._externalData = new BABYLON.StringDictionary();
  10149. }
  10150. return this._externalData.getOrAddWithFactory(key, factory);
  10151. };
  10152. /**
  10153. * Remove an externaly attached data from the Engine instance
  10154. * @param key the unique key that identifies the data
  10155. * @return true if the data was successfully removed, false if it doesn't exist
  10156. */
  10157. Engine.prototype.removeExternalData = function (key) {
  10158. if (!this._externalData) {
  10159. this._externalData = new BABYLON.StringDictionary();
  10160. }
  10161. return this._externalData.remove(key);
  10162. };
  10163. Engine.prototype.releaseInternalTexture = function (texture) {
  10164. if (!texture) {
  10165. return;
  10166. }
  10167. texture.references--;
  10168. // Final reference ?
  10169. if (texture.references === 0) {
  10170. var texturesCache = this.getLoadedTexturesCache();
  10171. var index = texturesCache.indexOf(texture);
  10172. if (index > -1) {
  10173. texturesCache.splice(index, 1);
  10174. }
  10175. this._releaseTexture(texture);
  10176. }
  10177. };
  10178. Engine.prototype.unbindAllAttributes = function () {
  10179. if (this._mustWipeVertexAttributes) {
  10180. this._mustWipeVertexAttributes = false;
  10181. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10182. this._gl.disableVertexAttribArray(i);
  10183. this._vertexAttribArraysEnabled[i] = false;
  10184. this._currentBufferPointers[i] = null;
  10185. }
  10186. return;
  10187. }
  10188. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10189. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10190. continue;
  10191. }
  10192. this._gl.disableVertexAttribArray(i);
  10193. this._vertexAttribArraysEnabled[i] = false;
  10194. this._currentBufferPointers[i] = null;
  10195. }
  10196. };
  10197. Engine.prototype.releaseEffects = function () {
  10198. for (var name in this._compiledEffects) {
  10199. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10200. }
  10201. this._compiledEffects = {};
  10202. };
  10203. // Dispose
  10204. Engine.prototype.dispose = function () {
  10205. this.hideLoadingUI();
  10206. this.stopRenderLoop();
  10207. // Empty texture
  10208. if (this._emptyTexture) {
  10209. this._releaseTexture(this._emptyTexture);
  10210. this._emptyTexture = null;
  10211. }
  10212. if (this._emptyCubeTexture) {
  10213. this._releaseTexture(this._emptyCubeTexture);
  10214. this._emptyCubeTexture = null;
  10215. }
  10216. // Release scenes
  10217. while (this.scenes.length) {
  10218. this.scenes[0].dispose();
  10219. }
  10220. // Release audio engine
  10221. if (Engine.audioEngine) {
  10222. Engine.audioEngine.dispose();
  10223. }
  10224. // Release effects
  10225. this.releaseEffects();
  10226. // Unbind
  10227. this.unbindAllAttributes();
  10228. this._gl = null;
  10229. //WebVR
  10230. this.disableVR();
  10231. // Events
  10232. window.removeEventListener("blur", this._onBlur);
  10233. window.removeEventListener("focus", this._onFocus);
  10234. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  10235. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10236. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10237. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10238. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10239. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10240. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10241. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10242. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10243. // Remove from Instances
  10244. var index = Engine.Instances.indexOf(this);
  10245. if (index >= 0) {
  10246. Engine.Instances.splice(index, 1);
  10247. }
  10248. };
  10249. // Loading screen
  10250. Engine.prototype.displayLoadingUI = function () {
  10251. var loadingScreen = this.loadingScreen;
  10252. if (loadingScreen) {
  10253. loadingScreen.displayLoadingUI();
  10254. }
  10255. };
  10256. Engine.prototype.hideLoadingUI = function () {
  10257. var loadingScreen = this.loadingScreen;
  10258. if (loadingScreen) {
  10259. loadingScreen.hideLoadingUI();
  10260. }
  10261. };
  10262. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10263. get: function () {
  10264. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  10265. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  10266. return this._loadingScreen;
  10267. },
  10268. set: function (loadingScreen) {
  10269. this._loadingScreen = loadingScreen;
  10270. },
  10271. enumerable: true,
  10272. configurable: true
  10273. });
  10274. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10275. set: function (text) {
  10276. this.loadingScreen.loadingUIText = text;
  10277. },
  10278. enumerable: true,
  10279. configurable: true
  10280. });
  10281. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10282. set: function (color) {
  10283. this.loadingScreen.loadingUIBackgroundColor = color;
  10284. },
  10285. enumerable: true,
  10286. configurable: true
  10287. });
  10288. Engine.prototype.attachContextLostEvent = function (callback) {
  10289. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10290. };
  10291. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10292. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10293. };
  10294. Engine.prototype.getVertexShaderSource = function (program) {
  10295. var shaders = this._gl.getAttachedShaders(program);
  10296. return this._gl.getShaderSource(shaders[0]);
  10297. };
  10298. Engine.prototype.getFragmentShaderSource = function (program) {
  10299. var shaders = this._gl.getAttachedShaders(program);
  10300. return this._gl.getShaderSource(shaders[1]);
  10301. };
  10302. // FPS
  10303. Engine.prototype.getFps = function () {
  10304. return this.fps;
  10305. };
  10306. Engine.prototype.getDeltaTime = function () {
  10307. return this.deltaTime;
  10308. };
  10309. Engine.prototype._measureFps = function () {
  10310. this.previousFramesDuration.push(BABYLON.Tools.Now);
  10311. var length = this.previousFramesDuration.length;
  10312. if (length >= 2) {
  10313. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  10314. }
  10315. if (length >= this.fpsRange) {
  10316. if (length > this.fpsRange) {
  10317. this.previousFramesDuration.splice(0, 1);
  10318. length = this.previousFramesDuration.length;
  10319. }
  10320. var sum = 0;
  10321. for (var id = 0; id < length - 1; id++) {
  10322. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  10323. }
  10324. this.fps = 1000.0 / (sum / (length - 1));
  10325. }
  10326. };
  10327. Engine.prototype._canRenderToFloatFramebuffer = function () {
  10328. if (this._webGLVersion > 1) {
  10329. return this._caps.colorBufferFloat;
  10330. }
  10331. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  10332. };
  10333. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  10334. if (this._webGLVersion > 1) {
  10335. return this._caps.colorBufferFloat;
  10336. }
  10337. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  10338. };
  10339. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  10340. Engine.prototype._canRenderToFramebuffer = function (type) {
  10341. var gl = this._gl;
  10342. //clear existing errors
  10343. while (gl.getError() !== gl.NO_ERROR) { }
  10344. var successful = true;
  10345. var texture = gl.createTexture();
  10346. gl.bindTexture(gl.TEXTURE_2D, texture);
  10347. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10348. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10349. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10350. var fb = gl.createFramebuffer();
  10351. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  10352. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  10353. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  10354. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  10355. successful = successful && (gl.getError() === gl.NO_ERROR);
  10356. //try render by clearing frame buffer's color buffer
  10357. if (successful) {
  10358. gl.clear(gl.COLOR_BUFFER_BIT);
  10359. successful = successful && (gl.getError() === gl.NO_ERROR);
  10360. }
  10361. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  10362. if (successful) {
  10363. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  10364. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10365. var readFormat = gl.RGBA;
  10366. var readType = gl.UNSIGNED_BYTE;
  10367. var buffer = new Uint8Array(4);
  10368. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  10369. successful = successful && (gl.getError() === gl.NO_ERROR);
  10370. }
  10371. //clean up
  10372. gl.deleteTexture(texture);
  10373. gl.deleteFramebuffer(fb);
  10374. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  10375. //clear accumulated errors
  10376. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  10377. return successful;
  10378. };
  10379. Engine.prototype._getWebGLTextureType = function (type) {
  10380. if (type === Engine.TEXTURETYPE_FLOAT) {
  10381. return this._gl.FLOAT;
  10382. }
  10383. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10384. // Add Half Float Constant.
  10385. return Engine.HALF_FLOAT_OES;
  10386. }
  10387. return this._gl.UNSIGNED_BYTE;
  10388. };
  10389. ;
  10390. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  10391. if (this._webGLVersion === 1) {
  10392. return this._gl.RGBA;
  10393. }
  10394. if (type === Engine.TEXTURETYPE_FLOAT) {
  10395. return Engine.RGBA32F;
  10396. }
  10397. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10398. return Engine.RGBA16F;
  10399. }
  10400. return this._gl.RGBA;
  10401. };
  10402. ;
  10403. // Statics
  10404. Engine.isSupported = function () {
  10405. try {
  10406. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  10407. if (navigator.isCocoonJS) {
  10408. return true;
  10409. }
  10410. var tempcanvas = document.createElement("canvas");
  10411. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  10412. return gl != null && !!window.WebGLRenderingContext;
  10413. }
  10414. catch (e) {
  10415. return false;
  10416. }
  10417. };
  10418. return Engine;
  10419. }());
  10420. Engine.Instances = new Array();
  10421. // Const statics
  10422. Engine._ALPHA_DISABLE = 0;
  10423. Engine._ALPHA_ADD = 1;
  10424. Engine._ALPHA_COMBINE = 2;
  10425. Engine._ALPHA_SUBTRACT = 3;
  10426. Engine._ALPHA_MULTIPLY = 4;
  10427. Engine._ALPHA_MAXIMIZED = 5;
  10428. Engine._ALPHA_ONEONE = 6;
  10429. Engine._ALPHA_PREMULTIPLIED = 7;
  10430. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  10431. Engine._ALPHA_INTERPOLATE = 9;
  10432. Engine._ALPHA_SCREENMODE = 10;
  10433. Engine._DELAYLOADSTATE_NONE = 0;
  10434. Engine._DELAYLOADSTATE_LOADED = 1;
  10435. Engine._DELAYLOADSTATE_LOADING = 2;
  10436. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  10437. Engine._TEXTUREFORMAT_ALPHA = 0;
  10438. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  10439. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  10440. Engine._TEXTUREFORMAT_RGB = 4;
  10441. Engine._TEXTUREFORMAT_RGBA = 5;
  10442. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  10443. Engine._TEXTURETYPE_FLOAT = 1;
  10444. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  10445. // Depht or Stencil test Constants.
  10446. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  10447. 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.
  10448. 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.
  10449. 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.
  10450. 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.
  10451. 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.
  10452. 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.
  10453. 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.
  10454. Engine.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10455. Engine.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10456. Engine.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10457. // Stencil Actions Constants.
  10458. Engine._KEEP = 0x1E00;
  10459. Engine._REPLACE = 0x1E01;
  10460. Engine._INCR = 0x1E02;
  10461. Engine._DECR = 0x1E03;
  10462. Engine._INVERT = 0x150A;
  10463. Engine._INCR_WRAP = 0x8507;
  10464. Engine._DECR_WRAP = 0x8508;
  10465. // Texture rescaling mode
  10466. Engine._SCALEMODE_FLOOR = 1;
  10467. Engine._SCALEMODE_NEAREST = 2;
  10468. Engine._SCALEMODE_CEILING = 3;
  10469. // Updatable statics so stick with vars here
  10470. Engine.CollisionsEpsilon = 0.001;
  10471. Engine.CodeRepository = "src/";
  10472. Engine.ShadersRepository = "src/Shaders/";
  10473. BABYLON.Engine = Engine;
  10474. })(BABYLON || (BABYLON = {}));
  10475. //# sourceMappingURL=babylon.engine.js.map
  10476. /// <reference path="Tools\babylon.decorators.ts" />
  10477. var BABYLON;
  10478. (function (BABYLON) {
  10479. /**
  10480. * Node is the basic class for all scene objects (Mesh, Light Camera).
  10481. */
  10482. var Node = (function () {
  10483. /**
  10484. * @constructor
  10485. * @param {string} name - the name and id to be given to this node
  10486. * @param {BABYLON.Scene} the scene this node will be added to
  10487. */
  10488. function Node(name, scene) {
  10489. this.state = "";
  10490. this.metadata = null;
  10491. this.doNotSerialize = false;
  10492. this.animations = new Array();
  10493. this._ranges = {};
  10494. this._childrenFlag = -1;
  10495. this._isEnabled = true;
  10496. this._isReady = true;
  10497. this._currentRenderId = -1;
  10498. this._parentRenderId = -1;
  10499. /**
  10500. * An event triggered when the mesh is disposed.
  10501. * @type {BABYLON.Observable}
  10502. */
  10503. this.onDisposeObservable = new BABYLON.Observable();
  10504. this.name = name;
  10505. this.id = name;
  10506. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  10507. this._initCache();
  10508. }
  10509. Object.defineProperty(Node.prototype, "parent", {
  10510. get: function () {
  10511. return this._parentNode;
  10512. },
  10513. set: function (parent) {
  10514. if (this._parentNode === parent) {
  10515. return;
  10516. }
  10517. if (this._parentNode) {
  10518. var index = this._parentNode._children.indexOf(this);
  10519. if (index !== -1) {
  10520. this._parentNode._children.splice(index, 1);
  10521. }
  10522. }
  10523. this._parentNode = parent;
  10524. if (this._parentNode) {
  10525. if (!this._parentNode._children) {
  10526. this._parentNode._children = new Array();
  10527. }
  10528. this._parentNode._children.push(this);
  10529. }
  10530. },
  10531. enumerable: true,
  10532. configurable: true
  10533. });
  10534. Node.prototype.getClassName = function () {
  10535. return "Node";
  10536. };
  10537. Object.defineProperty(Node.prototype, "onDispose", {
  10538. set: function (callback) {
  10539. if (this._onDisposeObserver) {
  10540. this.onDisposeObservable.remove(this._onDisposeObserver);
  10541. }
  10542. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10543. },
  10544. enumerable: true,
  10545. configurable: true
  10546. });
  10547. Node.prototype.getScene = function () {
  10548. return this._scene;
  10549. };
  10550. Node.prototype.getEngine = function () {
  10551. return this._scene.getEngine();
  10552. };
  10553. // override it in derived class
  10554. Node.prototype.getWorldMatrix = function () {
  10555. return BABYLON.Matrix.Identity();
  10556. };
  10557. // override it in derived class if you add new variables to the cache
  10558. // and call the parent class method
  10559. Node.prototype._initCache = function () {
  10560. this._cache = {};
  10561. this._cache.parent = undefined;
  10562. };
  10563. Node.prototype.updateCache = function (force) {
  10564. if (!force && this.isSynchronized())
  10565. return;
  10566. this._cache.parent = this.parent;
  10567. this._updateCache();
  10568. };
  10569. // override it in derived class if you add new variables to the cache
  10570. // and call the parent class method if !ignoreParentClass
  10571. Node.prototype._updateCache = function (ignoreParentClass) {
  10572. };
  10573. // override it in derived class if you add new variables to the cache
  10574. Node.prototype._isSynchronized = function () {
  10575. return true;
  10576. };
  10577. Node.prototype._markSyncedWithParent = function () {
  10578. this._parentRenderId = this.parent._currentRenderId;
  10579. };
  10580. Node.prototype.isSynchronizedWithParent = function () {
  10581. if (!this.parent) {
  10582. return true;
  10583. }
  10584. if (this._parentRenderId !== this.parent._currentRenderId) {
  10585. return false;
  10586. }
  10587. return this.parent.isSynchronized();
  10588. };
  10589. Node.prototype.isSynchronized = function (updateCache) {
  10590. var check = this.hasNewParent();
  10591. check = check || !this.isSynchronizedWithParent();
  10592. check = check || !this._isSynchronized();
  10593. if (updateCache)
  10594. this.updateCache(true);
  10595. return !check;
  10596. };
  10597. Node.prototype.hasNewParent = function (update) {
  10598. if (this._cache.parent === this.parent)
  10599. return false;
  10600. if (update)
  10601. this._cache.parent = this.parent;
  10602. return true;
  10603. };
  10604. /**
  10605. * Is this node ready to be used/rendered
  10606. * @return {boolean} is it ready
  10607. */
  10608. Node.prototype.isReady = function () {
  10609. return this._isReady;
  10610. };
  10611. /**
  10612. * Is this node enabled.
  10613. * If the node has a parent and is enabled, the parent will be inspected as well.
  10614. * @return {boolean} whether this node (and its parent) is enabled.
  10615. * @see setEnabled
  10616. */
  10617. Node.prototype.isEnabled = function () {
  10618. if (!this._isEnabled) {
  10619. return false;
  10620. }
  10621. if (this.parent) {
  10622. return this.parent.isEnabled();
  10623. }
  10624. return true;
  10625. };
  10626. /**
  10627. * Set the enabled state of this node.
  10628. * @param {boolean} value - the new enabled state
  10629. * @see isEnabled
  10630. */
  10631. Node.prototype.setEnabled = function (value) {
  10632. this._isEnabled = value;
  10633. };
  10634. /**
  10635. * Is this node a descendant of the given node.
  10636. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  10637. * @param {BABYLON.Node} ancestor - The parent node to inspect
  10638. * @see parent
  10639. */
  10640. Node.prototype.isDescendantOf = function (ancestor) {
  10641. if (this.parent) {
  10642. if (this.parent === ancestor) {
  10643. return true;
  10644. }
  10645. return this.parent.isDescendantOf(ancestor);
  10646. }
  10647. return false;
  10648. };
  10649. /**
  10650. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  10651. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  10652. * @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.
  10653. * @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.
  10654. */
  10655. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  10656. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  10657. if (!this._children) {
  10658. return;
  10659. }
  10660. for (var index = 0; index < this._children.length; index++) {
  10661. var item = this._children[index];
  10662. if (!predicate || predicate(item)) {
  10663. results.push(item);
  10664. }
  10665. if (!directDescendantsOnly) {
  10666. item._getDescendants(results, false, predicate);
  10667. }
  10668. }
  10669. };
  10670. /**
  10671. * Will return all nodes that have this node as ascendant.
  10672. * @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.
  10673. * @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.
  10674. * @return {BABYLON.Node[]} all children nodes of all types.
  10675. */
  10676. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  10677. var results = [];
  10678. this._getDescendants(results, directDescendantsOnly, predicate);
  10679. return results;
  10680. };
  10681. /**
  10682. * Get all child-meshes of this node.
  10683. */
  10684. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  10685. var results = [];
  10686. this._getDescendants(results, directDecendantsOnly, function (node) {
  10687. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  10688. });
  10689. return results;
  10690. };
  10691. /**
  10692. * Get all direct children of this node.
  10693. */
  10694. Node.prototype.getChildren = function (predicate) {
  10695. return this.getDescendants(true, predicate);
  10696. };
  10697. Node.prototype._setReady = function (state) {
  10698. if (state === this._isReady) {
  10699. return;
  10700. }
  10701. if (!state) {
  10702. this._isReady = false;
  10703. return;
  10704. }
  10705. this._isReady = true;
  10706. if (this.onReady) {
  10707. this.onReady(this);
  10708. }
  10709. };
  10710. Node.prototype.getAnimationByName = function (name) {
  10711. for (var i = 0; i < this.animations.length; i++) {
  10712. var animation = this.animations[i];
  10713. if (animation.name === name) {
  10714. return animation;
  10715. }
  10716. }
  10717. return null;
  10718. };
  10719. Node.prototype.createAnimationRange = function (name, from, to) {
  10720. // check name not already in use
  10721. if (!this._ranges[name]) {
  10722. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  10723. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10724. if (this.animations[i]) {
  10725. this.animations[i].createRange(name, from, to);
  10726. }
  10727. }
  10728. }
  10729. };
  10730. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  10731. if (deleteFrames === void 0) { deleteFrames = true; }
  10732. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10733. if (this.animations[i]) {
  10734. this.animations[i].deleteRange(name, deleteFrames);
  10735. }
  10736. }
  10737. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  10738. };
  10739. Node.prototype.getAnimationRange = function (name) {
  10740. return this._ranges[name];
  10741. };
  10742. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  10743. var range = this.getAnimationRange(name);
  10744. if (!range) {
  10745. return null;
  10746. }
  10747. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  10748. };
  10749. Node.prototype.serializeAnimationRanges = function () {
  10750. var serializationRanges = [];
  10751. for (var name in this._ranges) {
  10752. var range = {};
  10753. range.name = name;
  10754. range.from = this._ranges[name].from;
  10755. range.to = this._ranges[name].to;
  10756. serializationRanges.push(range);
  10757. }
  10758. return serializationRanges;
  10759. };
  10760. Node.prototype.dispose = function () {
  10761. this.parent = null;
  10762. // Callback
  10763. this.onDisposeObservable.notifyObservers(this);
  10764. this.onDisposeObservable.clear();
  10765. };
  10766. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  10767. if (parsedNode.ranges) {
  10768. for (var index = 0; index < parsedNode.ranges.length; index++) {
  10769. var data = parsedNode.ranges[index];
  10770. node.createAnimationRange(data.name, data.from, data.to);
  10771. }
  10772. }
  10773. };
  10774. return Node;
  10775. }());
  10776. __decorate([
  10777. BABYLON.serialize()
  10778. ], Node.prototype, "name", void 0);
  10779. __decorate([
  10780. BABYLON.serialize()
  10781. ], Node.prototype, "id", void 0);
  10782. __decorate([
  10783. BABYLON.serialize()
  10784. ], Node.prototype, "uniqueId", void 0);
  10785. __decorate([
  10786. BABYLON.serialize()
  10787. ], Node.prototype, "state", void 0);
  10788. __decorate([
  10789. BABYLON.serialize()
  10790. ], Node.prototype, "metadata", void 0);
  10791. BABYLON.Node = Node;
  10792. })(BABYLON || (BABYLON = {}));
  10793. //# sourceMappingURL=babylon.node.js.map
  10794. var BABYLON;
  10795. (function (BABYLON) {
  10796. var BoundingSphere = (function () {
  10797. function BoundingSphere(minimum, maximum) {
  10798. this.minimum = minimum;
  10799. this.maximum = maximum;
  10800. this._tempRadiusVector = BABYLON.Vector3.Zero();
  10801. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  10802. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  10803. this.radius = distance * 0.5;
  10804. this.centerWorld = BABYLON.Vector3.Zero();
  10805. this._update(BABYLON.Matrix.Identity());
  10806. }
  10807. // Methods
  10808. BoundingSphere.prototype._update = function (world) {
  10809. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  10810. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  10811. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  10812. };
  10813. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  10814. for (var i = 0; i < 6; i++) {
  10815. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  10816. return false;
  10817. }
  10818. return true;
  10819. };
  10820. BoundingSphere.prototype.intersectsPoint = function (point) {
  10821. var x = this.centerWorld.x - point.x;
  10822. var y = this.centerWorld.y - point.y;
  10823. var z = this.centerWorld.z - point.z;
  10824. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10825. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  10826. return false;
  10827. return true;
  10828. };
  10829. // Statics
  10830. BoundingSphere.Intersects = function (sphere0, sphere1) {
  10831. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  10832. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  10833. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  10834. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10835. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  10836. return false;
  10837. return true;
  10838. };
  10839. return BoundingSphere;
  10840. }());
  10841. BABYLON.BoundingSphere = BoundingSphere;
  10842. })(BABYLON || (BABYLON = {}));
  10843. //# sourceMappingURL=babylon.boundingSphere.js.map
  10844. var BABYLON;
  10845. (function (BABYLON) {
  10846. var BoundingBox = (function () {
  10847. function BoundingBox(minimum, maximum) {
  10848. this.minimum = minimum;
  10849. this.maximum = maximum;
  10850. this.vectors = new Array();
  10851. this.vectorsWorld = new Array();
  10852. // Bounding vectors
  10853. this.vectors.push(this.minimum.clone());
  10854. this.vectors.push(this.maximum.clone());
  10855. this.vectors.push(this.minimum.clone());
  10856. this.vectors[2].x = this.maximum.x;
  10857. this.vectors.push(this.minimum.clone());
  10858. this.vectors[3].y = this.maximum.y;
  10859. this.vectors.push(this.minimum.clone());
  10860. this.vectors[4].z = this.maximum.z;
  10861. this.vectors.push(this.maximum.clone());
  10862. this.vectors[5].z = this.minimum.z;
  10863. this.vectors.push(this.maximum.clone());
  10864. this.vectors[6].x = this.minimum.x;
  10865. this.vectors.push(this.maximum.clone());
  10866. this.vectors[7].y = this.minimum.y;
  10867. // OBB
  10868. this.center = this.maximum.add(this.minimum).scale(0.5);
  10869. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  10870. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  10871. // World
  10872. for (var index = 0; index < this.vectors.length; index++) {
  10873. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  10874. }
  10875. this.minimumWorld = BABYLON.Vector3.Zero();
  10876. this.maximumWorld = BABYLON.Vector3.Zero();
  10877. this.centerWorld = BABYLON.Vector3.Zero();
  10878. this.extendSizeWorld = BABYLON.Vector3.Zero();
  10879. this._update(BABYLON.Matrix.Identity());
  10880. }
  10881. // Methods
  10882. BoundingBox.prototype.getWorldMatrix = function () {
  10883. return this._worldMatrix;
  10884. };
  10885. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  10886. this._worldMatrix.copyFrom(matrix);
  10887. return this;
  10888. };
  10889. BoundingBox.prototype._update = function (world) {
  10890. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  10891. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  10892. for (var index = 0; index < this.vectors.length; index++) {
  10893. var v = this.vectorsWorld[index];
  10894. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  10895. if (v.x < this.minimumWorld.x)
  10896. this.minimumWorld.x = v.x;
  10897. if (v.y < this.minimumWorld.y)
  10898. this.minimumWorld.y = v.y;
  10899. if (v.z < this.minimumWorld.z)
  10900. this.minimumWorld.z = v.z;
  10901. if (v.x > this.maximumWorld.x)
  10902. this.maximumWorld.x = v.x;
  10903. if (v.y > this.maximumWorld.y)
  10904. this.maximumWorld.y = v.y;
  10905. if (v.z > this.maximumWorld.z)
  10906. this.maximumWorld.z = v.z;
  10907. }
  10908. // Extend
  10909. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  10910. this.extendSizeWorld.scaleInPlace(0.5);
  10911. // OBB
  10912. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  10913. this.centerWorld.scaleInPlace(0.5);
  10914. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  10915. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  10916. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  10917. this._worldMatrix = world;
  10918. };
  10919. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  10920. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  10921. };
  10922. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10923. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  10924. };
  10925. BoundingBox.prototype.intersectsPoint = function (point) {
  10926. var delta = -BABYLON.Epsilon;
  10927. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  10928. return false;
  10929. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  10930. return false;
  10931. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  10932. return false;
  10933. return true;
  10934. };
  10935. BoundingBox.prototype.intersectsSphere = function (sphere) {
  10936. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  10937. };
  10938. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  10939. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  10940. return false;
  10941. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  10942. return false;
  10943. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  10944. return false;
  10945. return true;
  10946. };
  10947. // Statics
  10948. BoundingBox.Intersects = function (box0, box1) {
  10949. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  10950. return false;
  10951. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  10952. return false;
  10953. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  10954. return false;
  10955. return true;
  10956. };
  10957. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  10958. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  10959. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  10960. return (num <= (sphereRadius * sphereRadius));
  10961. };
  10962. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  10963. for (var p = 0; p < 6; p++) {
  10964. for (var i = 0; i < 8; i++) {
  10965. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  10966. return false;
  10967. }
  10968. }
  10969. }
  10970. return true;
  10971. };
  10972. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  10973. for (var p = 0; p < 6; p++) {
  10974. var inCount = 8;
  10975. for (var i = 0; i < 8; i++) {
  10976. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  10977. --inCount;
  10978. }
  10979. else {
  10980. break;
  10981. }
  10982. }
  10983. if (inCount === 0)
  10984. return false;
  10985. }
  10986. return true;
  10987. };
  10988. return BoundingBox;
  10989. }());
  10990. BABYLON.BoundingBox = BoundingBox;
  10991. })(BABYLON || (BABYLON = {}));
  10992. //# sourceMappingURL=babylon.boundingBox.js.map
  10993. var BABYLON;
  10994. (function (BABYLON) {
  10995. var computeBoxExtents = function (axis, box) {
  10996. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  10997. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  10998. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  10999. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11000. var r = r0 + r1 + r2;
  11001. return {
  11002. min: p - r,
  11003. max: p + r
  11004. };
  11005. };
  11006. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11007. var axisOverlap = function (axis, box0, box1) {
  11008. var result0 = computeBoxExtents(axis, box0);
  11009. var result1 = computeBoxExtents(axis, box1);
  11010. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11011. };
  11012. var BoundingInfo = (function () {
  11013. function BoundingInfo(minimum, maximum) {
  11014. this.minimum = minimum;
  11015. this.maximum = maximum;
  11016. this._isLocked = false;
  11017. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11018. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11019. }
  11020. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11021. get: function () {
  11022. return this._isLocked;
  11023. },
  11024. set: function (value) {
  11025. this._isLocked = value;
  11026. },
  11027. enumerable: true,
  11028. configurable: true
  11029. });
  11030. // Methods
  11031. BoundingInfo.prototype.update = function (world) {
  11032. if (this._isLocked) {
  11033. return;
  11034. }
  11035. this.boundingBox._update(world);
  11036. this.boundingSphere._update(world);
  11037. };
  11038. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11039. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11040. return false;
  11041. return this.boundingBox.isInFrustum(frustumPlanes);
  11042. };
  11043. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11044. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11045. };
  11046. BoundingInfo.prototype._checkCollision = function (collider) {
  11047. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11048. };
  11049. BoundingInfo.prototype.intersectsPoint = function (point) {
  11050. if (!this.boundingSphere.centerWorld) {
  11051. return false;
  11052. }
  11053. if (!this.boundingSphere.intersectsPoint(point)) {
  11054. return false;
  11055. }
  11056. if (!this.boundingBox.intersectsPoint(point)) {
  11057. return false;
  11058. }
  11059. return true;
  11060. };
  11061. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11062. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11063. return false;
  11064. }
  11065. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11066. return false;
  11067. }
  11068. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11069. return false;
  11070. }
  11071. if (!precise) {
  11072. return true;
  11073. }
  11074. var box0 = this.boundingBox;
  11075. var box1 = boundingInfo.boundingBox;
  11076. if (!axisOverlap(box0.directions[0], box0, box1))
  11077. return false;
  11078. if (!axisOverlap(box0.directions[1], box0, box1))
  11079. return false;
  11080. if (!axisOverlap(box0.directions[2], box0, box1))
  11081. return false;
  11082. if (!axisOverlap(box1.directions[0], box0, box1))
  11083. return false;
  11084. if (!axisOverlap(box1.directions[1], box0, box1))
  11085. return false;
  11086. if (!axisOverlap(box1.directions[2], box0, box1))
  11087. return false;
  11088. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11089. return false;
  11090. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11091. return false;
  11092. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11093. return false;
  11094. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11095. return false;
  11096. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11097. return false;
  11098. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11099. return false;
  11100. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11101. return false;
  11102. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11103. return false;
  11104. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11105. return false;
  11106. return true;
  11107. };
  11108. return BoundingInfo;
  11109. }());
  11110. BABYLON.BoundingInfo = BoundingInfo;
  11111. })(BABYLON || (BABYLON = {}));
  11112. //# sourceMappingURL=babylon.boundingInfo.js.map
  11113. var BABYLON;
  11114. (function (BABYLON) {
  11115. var AbstractMesh = (function (_super) {
  11116. __extends(AbstractMesh, _super);
  11117. // Constructor
  11118. function AbstractMesh(name, scene) {
  11119. var _this = _super.call(this, name, scene) || this;
  11120. _this._facetNb = 0; // facet number
  11121. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  11122. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  11123. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  11124. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  11125. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  11126. _this._subDiv = {
  11127. max: 1,
  11128. X: 1,
  11129. Y: 1,
  11130. Z: 1
  11131. };
  11132. // Events
  11133. /**
  11134. * An event triggered when this mesh collides with another one
  11135. * @type {BABYLON.Observable}
  11136. */
  11137. _this.onCollideObservable = new BABYLON.Observable();
  11138. /**
  11139. * An event triggered when the collision's position changes
  11140. * @type {BABYLON.Observable}
  11141. */
  11142. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  11143. /**
  11144. * An event triggered after the world matrix is updated
  11145. * @type {BABYLON.Observable}
  11146. */
  11147. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  11148. // Properties
  11149. _this.definedFacingForward = true; // orientation for POV movement & rotation
  11150. _this.position = new BABYLON.Vector3(0.0, 0.0, 0.0);
  11151. _this._rotation = new BABYLON.Vector3(0.0, 0.0, 0.0);
  11152. _this._scaling = new BABYLON.Vector3(1.0, 1.0, 1.0);
  11153. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  11154. _this.visibility = 1.0;
  11155. _this.alphaIndex = Number.MAX_VALUE;
  11156. _this.infiniteDistance = false;
  11157. _this.isVisible = true;
  11158. _this.isPickable = true;
  11159. _this.showBoundingBox = false;
  11160. _this.showSubMeshesBoundingBox = false;
  11161. _this.isBlocker = false;
  11162. _this.renderingGroupId = 0;
  11163. _this._receiveShadows = false;
  11164. _this.renderOutline = false;
  11165. _this.outlineColor = BABYLON.Color3.Red();
  11166. _this.outlineWidth = 0.02;
  11167. _this.renderOverlay = false;
  11168. _this.overlayColor = BABYLON.Color3.Red();
  11169. _this.overlayAlpha = 0.5;
  11170. _this._hasVertexAlpha = false;
  11171. _this._useVertexColors = true;
  11172. _this._computeBonesUsingShaders = true;
  11173. _this._numBoneInfluencers = 4;
  11174. _this._applyFog = true;
  11175. _this.scalingDeterminant = 1;
  11176. _this.useOctreeForRenderingSelection = true;
  11177. _this.useOctreeForPicking = true;
  11178. _this.useOctreeForCollisions = true;
  11179. _this.layerMask = 0x0FFFFFFF;
  11180. /**
  11181. * True if the mesh must be rendered in any case.
  11182. */
  11183. _this.alwaysSelectAsActiveMesh = false;
  11184. // Collisions
  11185. _this._checkCollisions = false;
  11186. _this._collisionMask = -1;
  11187. _this._collisionGroup = -1;
  11188. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11189. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  11190. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11191. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11192. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11193. // Edges
  11194. _this.edgesWidth = 1;
  11195. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  11196. // Cache
  11197. _this._localWorld = BABYLON.Matrix.Zero();
  11198. _this._worldMatrix = BABYLON.Matrix.Zero();
  11199. _this._absolutePosition = BABYLON.Vector3.Zero();
  11200. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  11201. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  11202. _this._isDirty = false;
  11203. _this._pivotMatrix = BABYLON.Matrix.Identity();
  11204. _this._isDisposed = false;
  11205. _this._renderId = 0;
  11206. _this._intersectionsInProgress = new Array();
  11207. _this._isWorldMatrixFrozen = false;
  11208. _this._unIndexed = false;
  11209. _this._lightSources = new Array();
  11210. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11211. if (collidedMesh === void 0) { collidedMesh = null; }
  11212. //TODO move this to the collision coordinator!
  11213. if (_this.getScene().workerCollisions)
  11214. newPosition.multiplyInPlace(_this._collider.radius);
  11215. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  11216. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  11217. _this.position.addInPlace(_this._diffPositionForCollisions);
  11218. }
  11219. if (collidedMesh) {
  11220. _this.onCollideObservable.notifyObservers(collidedMesh);
  11221. }
  11222. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  11223. };
  11224. _this.getScene().addMesh(_this);
  11225. _this._resyncLightSources();
  11226. return _this;
  11227. }
  11228. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  11229. get: function () {
  11230. return AbstractMesh._BILLBOARDMODE_NONE;
  11231. },
  11232. enumerable: true,
  11233. configurable: true
  11234. });
  11235. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  11236. get: function () {
  11237. return AbstractMesh._BILLBOARDMODE_X;
  11238. },
  11239. enumerable: true,
  11240. configurable: true
  11241. });
  11242. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  11243. get: function () {
  11244. return AbstractMesh._BILLBOARDMODE_Y;
  11245. },
  11246. enumerable: true,
  11247. configurable: true
  11248. });
  11249. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  11250. get: function () {
  11251. return AbstractMesh._BILLBOARDMODE_Z;
  11252. },
  11253. enumerable: true,
  11254. configurable: true
  11255. });
  11256. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  11257. get: function () {
  11258. return AbstractMesh._BILLBOARDMODE_ALL;
  11259. },
  11260. enumerable: true,
  11261. configurable: true
  11262. });
  11263. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  11264. /**
  11265. * Read-only : the number of facets in the mesh
  11266. */
  11267. get: function () {
  11268. return this._facetNb;
  11269. },
  11270. enumerable: true,
  11271. configurable: true
  11272. });
  11273. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  11274. /**
  11275. * The number (integer) of subdivisions per axis in the partioning space
  11276. */
  11277. get: function () {
  11278. return this._partitioningSubdivisions;
  11279. },
  11280. set: function (nb) {
  11281. this._partitioningSubdivisions = nb;
  11282. },
  11283. enumerable: true,
  11284. configurable: true
  11285. });
  11286. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  11287. /**
  11288. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  11289. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  11290. */
  11291. get: function () {
  11292. return this._partitioningBBoxRatio;
  11293. },
  11294. set: function (ratio) {
  11295. this._partitioningBBoxRatio = ratio;
  11296. },
  11297. enumerable: true,
  11298. configurable: true
  11299. });
  11300. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  11301. /**
  11302. * Read-only boolean : is the feature facetData enabled ?
  11303. */
  11304. get: function () {
  11305. return this._facetDataEnabled;
  11306. },
  11307. enumerable: true,
  11308. configurable: true
  11309. });
  11310. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  11311. set: function (callback) {
  11312. if (this._onCollideObserver) {
  11313. this.onCollideObservable.remove(this._onCollideObserver);
  11314. }
  11315. this._onCollideObserver = this.onCollideObservable.add(callback);
  11316. },
  11317. enumerable: true,
  11318. configurable: true
  11319. });
  11320. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  11321. set: function (callback) {
  11322. if (this._onCollisionPositionChangeObserver) {
  11323. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  11324. }
  11325. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  11326. },
  11327. enumerable: true,
  11328. configurable: true
  11329. });
  11330. Object.defineProperty(AbstractMesh.prototype, "material", {
  11331. get: function () {
  11332. return this._material;
  11333. },
  11334. set: function (value) {
  11335. if (this._material === value) {
  11336. return;
  11337. }
  11338. this._material = value;
  11339. if (!this.subMeshes) {
  11340. return;
  11341. }
  11342. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11343. var subMesh = _a[_i];
  11344. subMesh.setEffect(null);
  11345. }
  11346. },
  11347. enumerable: true,
  11348. configurable: true
  11349. });
  11350. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  11351. get: function () {
  11352. return this._receiveShadows;
  11353. },
  11354. set: function (value) {
  11355. if (this._receiveShadows === value) {
  11356. return;
  11357. }
  11358. this._receiveShadows = value;
  11359. this._markSubMeshesAsLightDirty();
  11360. },
  11361. enumerable: true,
  11362. configurable: true
  11363. });
  11364. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  11365. get: function () {
  11366. return this._hasVertexAlpha;
  11367. },
  11368. set: function (value) {
  11369. if (this._hasVertexAlpha === value) {
  11370. return;
  11371. }
  11372. this._hasVertexAlpha = value;
  11373. this._markSubMeshesAsAttributesDirty();
  11374. },
  11375. enumerable: true,
  11376. configurable: true
  11377. });
  11378. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  11379. get: function () {
  11380. return this._useVertexColors;
  11381. },
  11382. set: function (value) {
  11383. if (this._useVertexColors === value) {
  11384. return;
  11385. }
  11386. this._useVertexColors = value;
  11387. this._markSubMeshesAsAttributesDirty();
  11388. },
  11389. enumerable: true,
  11390. configurable: true
  11391. });
  11392. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  11393. get: function () {
  11394. return this._computeBonesUsingShaders;
  11395. },
  11396. set: function (value) {
  11397. if (this._computeBonesUsingShaders === value) {
  11398. return;
  11399. }
  11400. this._computeBonesUsingShaders = value;
  11401. this._markSubMeshesAsAttributesDirty();
  11402. },
  11403. enumerable: true,
  11404. configurable: true
  11405. });
  11406. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  11407. get: function () {
  11408. return this._numBoneInfluencers;
  11409. },
  11410. set: function (value) {
  11411. if (this._numBoneInfluencers === value) {
  11412. return;
  11413. }
  11414. this._numBoneInfluencers = value;
  11415. this._markSubMeshesAsAttributesDirty();
  11416. },
  11417. enumerable: true,
  11418. configurable: true
  11419. });
  11420. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  11421. get: function () {
  11422. return this._applyFog;
  11423. },
  11424. set: function (value) {
  11425. if (this._applyFog === value) {
  11426. return;
  11427. }
  11428. this._applyFog = value;
  11429. this._markSubMeshesAsMiscDirty();
  11430. },
  11431. enumerable: true,
  11432. configurable: true
  11433. });
  11434. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  11435. get: function () {
  11436. return this._collisionMask;
  11437. },
  11438. set: function (mask) {
  11439. this._collisionMask = !isNaN(mask) ? mask : -1;
  11440. },
  11441. enumerable: true,
  11442. configurable: true
  11443. });
  11444. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  11445. get: function () {
  11446. return this._collisionGroup;
  11447. },
  11448. set: function (mask) {
  11449. this._collisionGroup = !isNaN(mask) ? mask : -1;
  11450. },
  11451. enumerable: true,
  11452. configurable: true
  11453. });
  11454. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  11455. get: function () {
  11456. return null;
  11457. },
  11458. enumerable: true,
  11459. configurable: true
  11460. });
  11461. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  11462. get: function () {
  11463. return this._skeleton;
  11464. },
  11465. set: function (value) {
  11466. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  11467. this._skeleton._unregisterMeshWithPoseMatrix(this);
  11468. }
  11469. if (value && value.needInitialSkinMatrix) {
  11470. value._registerMeshWithPoseMatrix(this);
  11471. }
  11472. this._skeleton = value;
  11473. if (!this._skeleton) {
  11474. this._bonesTransformMatrices = null;
  11475. }
  11476. this._markSubMeshesAsAttributesDirty();
  11477. },
  11478. enumerable: true,
  11479. configurable: true
  11480. });
  11481. /**
  11482. * Returns the string "AbstractMesh"
  11483. */
  11484. AbstractMesh.prototype.getClassName = function () {
  11485. return "AbstractMesh";
  11486. };
  11487. /**
  11488. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11489. */
  11490. AbstractMesh.prototype.toString = function (fullDetails) {
  11491. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  11492. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  11493. if (this._skeleton) {
  11494. ret += ", skeleton: " + this._skeleton.name;
  11495. }
  11496. if (fullDetails) {
  11497. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  11498. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  11499. }
  11500. return ret;
  11501. };
  11502. AbstractMesh.prototype._resyncLightSources = function () {
  11503. this._lightSources.length = 0;
  11504. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  11505. var light = _a[_i];
  11506. if (!light.isEnabled()) {
  11507. continue;
  11508. }
  11509. if (light.canAffectMesh(this)) {
  11510. this._lightSources.push(light);
  11511. }
  11512. }
  11513. this._markSubMeshesAsLightDirty();
  11514. };
  11515. AbstractMesh.prototype._resyncLighSource = function (light) {
  11516. var isIn = light.isEnabled() && light.canAffectMesh(this);
  11517. var index = this._lightSources.indexOf(light);
  11518. if (index === -1) {
  11519. if (!isIn) {
  11520. return;
  11521. }
  11522. this._lightSources.push(light);
  11523. }
  11524. else {
  11525. if (isIn) {
  11526. return;
  11527. }
  11528. this._lightSources.splice(index, 1);
  11529. }
  11530. this._markSubMeshesAsLightDirty();
  11531. };
  11532. AbstractMesh.prototype._removeLightSource = function (light) {
  11533. var index = this._lightSources.indexOf(light);
  11534. if (index === -1) {
  11535. return;
  11536. }
  11537. this._lightSources.splice(index, 1);
  11538. };
  11539. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  11540. if (!this.subMeshes) {
  11541. return;
  11542. }
  11543. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11544. var subMesh = _a[_i];
  11545. if (subMesh._materialDefines) {
  11546. func(subMesh._materialDefines);
  11547. }
  11548. }
  11549. };
  11550. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  11551. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  11552. };
  11553. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  11554. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  11555. };
  11556. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  11557. if (!this.subMeshes) {
  11558. return;
  11559. }
  11560. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11561. var subMesh = _a[_i];
  11562. var material = subMesh.getMaterial();
  11563. if (material) {
  11564. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  11565. }
  11566. }
  11567. };
  11568. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  11569. /**
  11570. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  11571. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  11572. * Default : (0.0, 0.0, 0.0)
  11573. */
  11574. get: function () {
  11575. return this._rotation;
  11576. },
  11577. set: function (newRotation) {
  11578. this._rotation = newRotation;
  11579. },
  11580. enumerable: true,
  11581. configurable: true
  11582. });
  11583. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  11584. /**
  11585. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  11586. * Default : (1.0, 1.0, 1.0)
  11587. */
  11588. get: function () {
  11589. return this._scaling;
  11590. },
  11591. set: function (newScaling) {
  11592. this._scaling = newScaling;
  11593. if (this.physicsImpostor) {
  11594. this.physicsImpostor.forceUpdate();
  11595. }
  11596. },
  11597. enumerable: true,
  11598. configurable: true
  11599. });
  11600. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  11601. /**
  11602. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  11603. * It's null by default.
  11604. * 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)
  11605. */
  11606. get: function () {
  11607. return this._rotationQuaternion;
  11608. },
  11609. set: function (quaternion) {
  11610. this._rotationQuaternion = quaternion;
  11611. //reset the rotation vector.
  11612. if (quaternion && this.rotation.length()) {
  11613. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  11614. }
  11615. },
  11616. enumerable: true,
  11617. configurable: true
  11618. });
  11619. // Methods
  11620. /**
  11621. * Copies the paramater passed Matrix into the mesh Pose matrix.
  11622. * Returns the AbstractMesh.
  11623. */
  11624. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  11625. this._poseMatrix.copyFrom(matrix);
  11626. return this;
  11627. };
  11628. /**
  11629. * Returns the mesh Pose matrix.
  11630. * Returned object : Matrix
  11631. */
  11632. AbstractMesh.prototype.getPoseMatrix = function () {
  11633. return this._poseMatrix;
  11634. };
  11635. /**
  11636. * Disables the mesh edger rendering mode.
  11637. * Returns the AbstractMesh.
  11638. */
  11639. AbstractMesh.prototype.disableEdgesRendering = function () {
  11640. if (this._edgesRenderer !== undefined) {
  11641. this._edgesRenderer.dispose();
  11642. this._edgesRenderer = undefined;
  11643. }
  11644. return this;
  11645. };
  11646. /**
  11647. * Enables the edge rendering mode on the mesh.
  11648. * This mode makes the mesh edges visible.
  11649. * Returns the AbstractMesh.
  11650. */
  11651. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  11652. if (epsilon === void 0) { epsilon = 0.95; }
  11653. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  11654. this.disableEdgesRendering();
  11655. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  11656. return this;
  11657. };
  11658. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  11659. /**
  11660. * Returns true if the mesh is blocked. Used by the class Mesh.
  11661. * Returns the boolean `false` by default.
  11662. */
  11663. get: function () {
  11664. return false;
  11665. },
  11666. enumerable: true,
  11667. configurable: true
  11668. });
  11669. /**
  11670. * Returns the mesh itself by default, used by the class Mesh.
  11671. * Returned type : AbstractMesh
  11672. */
  11673. AbstractMesh.prototype.getLOD = function (camera) {
  11674. return this;
  11675. };
  11676. /**
  11677. * Returns 0 by default, used by the class Mesh.
  11678. * Returns an integer.
  11679. */
  11680. AbstractMesh.prototype.getTotalVertices = function () {
  11681. return 0;
  11682. };
  11683. /**
  11684. * Returns null by default, used by the class Mesh.
  11685. * Returned type : integer array
  11686. */
  11687. AbstractMesh.prototype.getIndices = function () {
  11688. return null;
  11689. };
  11690. /**
  11691. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  11692. * Returned type : float array or Float32Array
  11693. */
  11694. AbstractMesh.prototype.getVerticesData = function (kind) {
  11695. return null;
  11696. };
  11697. /**
  11698. * Sets the vertex data of the mesh geometry for the requested `kind`.
  11699. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  11700. * The `data` are either a numeric array either a Float32Array.
  11701. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  11702. * 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).
  11703. * Note that a new underlying VertexBuffer object is created each call.
  11704. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  11705. *
  11706. * Possible `kind` values :
  11707. * - BABYLON.VertexBuffer.PositionKind
  11708. * - BABYLON.VertexBuffer.UVKind
  11709. * - BABYLON.VertexBuffer.UV2Kind
  11710. * - BABYLON.VertexBuffer.UV3Kind
  11711. * - BABYLON.VertexBuffer.UV4Kind
  11712. * - BABYLON.VertexBuffer.UV5Kind
  11713. * - BABYLON.VertexBuffer.UV6Kind
  11714. * - BABYLON.VertexBuffer.ColorKind
  11715. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11716. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11717. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11718. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11719. *
  11720. * Returns the Mesh.
  11721. */
  11722. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  11723. return null;
  11724. };
  11725. /**
  11726. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  11727. * If the mesh has no geometry, it is simply returned as it is.
  11728. * The `data` are either a numeric array either a Float32Array.
  11729. * No new underlying VertexBuffer object is created.
  11730. * 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.
  11731. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  11732. *
  11733. * Possible `kind` values :
  11734. * - BABYLON.VertexBuffer.PositionKind
  11735. * - BABYLON.VertexBuffer.UVKind
  11736. * - BABYLON.VertexBuffer.UV2Kind
  11737. * - BABYLON.VertexBuffer.UV3Kind
  11738. * - BABYLON.VertexBuffer.UV4Kind
  11739. * - BABYLON.VertexBuffer.UV5Kind
  11740. * - BABYLON.VertexBuffer.UV6Kind
  11741. * - BABYLON.VertexBuffer.ColorKind
  11742. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11743. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11744. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11745. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11746. *
  11747. * Returns the Mesh.
  11748. */
  11749. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  11750. return null;
  11751. };
  11752. /**
  11753. * Sets the mesh indices.
  11754. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  11755. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  11756. * This method creates a new index buffer each call.
  11757. * Returns the Mesh.
  11758. */
  11759. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  11760. return null;
  11761. };
  11762. /** Returns false by default, used by the class Mesh.
  11763. * Returns a boolean
  11764. */
  11765. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  11766. return false;
  11767. };
  11768. /**
  11769. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  11770. * Returns a BoundingInfo
  11771. */
  11772. AbstractMesh.prototype.getBoundingInfo = function () {
  11773. if (this._masterMesh) {
  11774. return this._masterMesh.getBoundingInfo();
  11775. }
  11776. if (!this._boundingInfo) {
  11777. this._updateBoundingInfo();
  11778. }
  11779. return this._boundingInfo;
  11780. };
  11781. /**
  11782. * Sets a mesh new object BoundingInfo.
  11783. * Returns the AbstractMesh.
  11784. */
  11785. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  11786. this._boundingInfo = boundingInfo;
  11787. return this;
  11788. };
  11789. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  11790. get: function () {
  11791. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  11792. },
  11793. enumerable: true,
  11794. configurable: true
  11795. });
  11796. AbstractMesh.prototype._preActivate = function () {
  11797. };
  11798. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  11799. };
  11800. AbstractMesh.prototype._activate = function (renderId) {
  11801. this._renderId = renderId;
  11802. };
  11803. /**
  11804. * Returns the last update of the World matrix
  11805. * Returns a Matrix.
  11806. */
  11807. AbstractMesh.prototype.getWorldMatrix = function () {
  11808. if (this._masterMesh) {
  11809. return this._masterMesh.getWorldMatrix();
  11810. }
  11811. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  11812. this.computeWorldMatrix();
  11813. }
  11814. return this._worldMatrix;
  11815. };
  11816. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  11817. /**
  11818. * Returns directly the last state of the mesh World matrix.
  11819. * A Matrix is returned.
  11820. */
  11821. get: function () {
  11822. return this._worldMatrix;
  11823. },
  11824. enumerable: true,
  11825. configurable: true
  11826. });
  11827. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  11828. /**
  11829. * Returns the current mesh absolute position.
  11830. * Retuns a Vector3.
  11831. */
  11832. get: function () {
  11833. return this._absolutePosition;
  11834. },
  11835. enumerable: true,
  11836. configurable: true
  11837. });
  11838. /**
  11839. * Prevents the World matrix to be computed any longer.
  11840. * Returns the AbstractMesh.
  11841. */
  11842. AbstractMesh.prototype.freezeWorldMatrix = function () {
  11843. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  11844. this.computeWorldMatrix(true);
  11845. this._isWorldMatrixFrozen = true;
  11846. return this;
  11847. };
  11848. /**
  11849. * Allows back the World matrix computation.
  11850. * Returns the AbstractMesh.
  11851. */
  11852. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  11853. this._isWorldMatrixFrozen = false;
  11854. this.computeWorldMatrix(true);
  11855. return this;
  11856. };
  11857. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  11858. /**
  11859. * True if the World matrix has been frozen.
  11860. * Returns a boolean.
  11861. */
  11862. get: function () {
  11863. return this._isWorldMatrixFrozen;
  11864. },
  11865. enumerable: true,
  11866. configurable: true
  11867. });
  11868. /**
  11869. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  11870. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11871. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  11872. * The passed axis is also normalized.
  11873. * Returns the AbstractMesh.
  11874. */
  11875. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  11876. axis.normalize();
  11877. if (!this.rotationQuaternion) {
  11878. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11879. this.rotation = BABYLON.Vector3.Zero();
  11880. }
  11881. var rotationQuaternion;
  11882. if (!space || space === BABYLON.Space.LOCAL) {
  11883. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11884. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  11885. }
  11886. else {
  11887. if (this.parent) {
  11888. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11889. invertParentWorldMatrix.invert();
  11890. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  11891. }
  11892. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11893. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  11894. }
  11895. return this;
  11896. };
  11897. /**
  11898. * Translates the mesh along the axis vector for the passed distance in the given space.
  11899. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11900. * Returns the AbstractMesh.
  11901. */
  11902. AbstractMesh.prototype.translate = function (axis, distance, space) {
  11903. var displacementVector = axis.scale(distance);
  11904. if (!space || space === BABYLON.Space.LOCAL) {
  11905. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  11906. this.setPositionWithLocalVector(tempV3);
  11907. }
  11908. else {
  11909. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  11910. }
  11911. return this;
  11912. };
  11913. /**
  11914. * Adds a rotation step to the mesh current rotation.
  11915. * x, y, z are Euler angles expressed in radians.
  11916. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  11917. * This means this rotation is made in the mesh local space only.
  11918. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  11919. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  11920. * ```javascript
  11921. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  11922. * ```
  11923. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  11924. * 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.
  11925. * Returns the AbstractMesh.
  11926. */
  11927. AbstractMesh.prototype.addRotation = function (x, y, z) {
  11928. var rotationQuaternion;
  11929. if (this.rotationQuaternion) {
  11930. rotationQuaternion = this.rotationQuaternion;
  11931. }
  11932. else {
  11933. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  11934. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  11935. }
  11936. var accumulation = BABYLON.Tmp.Quaternion[0];
  11937. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  11938. rotationQuaternion.multiplyInPlace(accumulation);
  11939. if (!this.rotationQuaternion) {
  11940. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  11941. }
  11942. return this;
  11943. };
  11944. /**
  11945. * Retuns the mesh absolute position in the World.
  11946. * Returns a Vector3.
  11947. */
  11948. AbstractMesh.prototype.getAbsolutePosition = function () {
  11949. this.computeWorldMatrix();
  11950. return this._absolutePosition;
  11951. };
  11952. /**
  11953. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  11954. * Returns the AbstractMesh.
  11955. */
  11956. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  11957. if (!absolutePosition) {
  11958. return;
  11959. }
  11960. var absolutePositionX;
  11961. var absolutePositionY;
  11962. var absolutePositionZ;
  11963. if (absolutePosition.x === undefined) {
  11964. if (arguments.length < 3) {
  11965. return;
  11966. }
  11967. absolutePositionX = arguments[0];
  11968. absolutePositionY = arguments[1];
  11969. absolutePositionZ = arguments[2];
  11970. }
  11971. else {
  11972. absolutePositionX = absolutePosition.x;
  11973. absolutePositionY = absolutePosition.y;
  11974. absolutePositionZ = absolutePosition.z;
  11975. }
  11976. if (this.parent) {
  11977. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11978. invertParentWorldMatrix.invert();
  11979. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  11980. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  11981. }
  11982. else {
  11983. this.position.x = absolutePositionX;
  11984. this.position.y = absolutePositionY;
  11985. this.position.z = absolutePositionZ;
  11986. }
  11987. return this;
  11988. };
  11989. // ================================== Point of View Movement =================================
  11990. /**
  11991. * Perform relative position change from the point of view of behind the front of the mesh.
  11992. * This is performed taking into account the meshes current rotation, so you do not have to care.
  11993. * Supports definition of mesh facing forward or backward.
  11994. * @param {number} amountRight
  11995. * @param {number} amountUp
  11996. * @param {number} amountForward
  11997. *
  11998. * Returns the AbstractMesh.
  11999. */
  12000. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  12001. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  12002. return this;
  12003. };
  12004. /**
  12005. * Calculate relative position change from the point of view of behind the front of the mesh.
  12006. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12007. * Supports definition of mesh facing forward or backward.
  12008. * @param {number} amountRight
  12009. * @param {number} amountUp
  12010. * @param {number} amountForward
  12011. *
  12012. * Returns a new Vector3.
  12013. */
  12014. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  12015. var rotMatrix = new BABYLON.Matrix();
  12016. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12017. rotQuaternion.toRotationMatrix(rotMatrix);
  12018. var translationDelta = BABYLON.Vector3.Zero();
  12019. var defForwardMult = this.definedFacingForward ? -1 : 1;
  12020. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  12021. return translationDelta;
  12022. };
  12023. // ================================== Point of View Rotation =================================
  12024. /**
  12025. * Perform relative rotation change from the point of view of behind the front of the mesh.
  12026. * Supports definition of mesh facing forward or backward.
  12027. * @param {number} flipBack
  12028. * @param {number} twirlClockwise
  12029. * @param {number} tiltRight
  12030. *
  12031. * Returns the AbstractMesh.
  12032. */
  12033. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12034. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  12035. return this;
  12036. };
  12037. /**
  12038. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  12039. * Supports definition of mesh facing forward or backward.
  12040. * @param {number} flipBack
  12041. * @param {number} twirlClockwise
  12042. * @param {number} tiltRight
  12043. *
  12044. * Returns a new Vector3.
  12045. */
  12046. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12047. var defForwardMult = this.definedFacingForward ? 1 : -1;
  12048. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  12049. };
  12050. /**
  12051. * Sets a new pivot matrix to the mesh.
  12052. * Returns the AbstractMesh.
  12053. */
  12054. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  12055. this._pivotMatrix = matrix;
  12056. this._cache.pivotMatrixUpdated = true;
  12057. return this;
  12058. };
  12059. /**
  12060. * Returns the mesh pivot matrix.
  12061. * Default : Identity.
  12062. * A Matrix is returned.
  12063. */
  12064. AbstractMesh.prototype.getPivotMatrix = function () {
  12065. return this._pivotMatrix;
  12066. };
  12067. AbstractMesh.prototype._isSynchronized = function () {
  12068. if (this._isDirty) {
  12069. return false;
  12070. }
  12071. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12072. return false;
  12073. if (this._cache.pivotMatrixUpdated) {
  12074. return false;
  12075. }
  12076. if (this.infiniteDistance) {
  12077. return false;
  12078. }
  12079. if (!this._cache.position.equals(this.position))
  12080. return false;
  12081. if (this.rotationQuaternion) {
  12082. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12083. return false;
  12084. }
  12085. if (!this._cache.rotation.equals(this.rotation))
  12086. return false;
  12087. if (!this._cache.scaling.equals(this.scaling))
  12088. return false;
  12089. return true;
  12090. };
  12091. AbstractMesh.prototype._initCache = function () {
  12092. _super.prototype._initCache.call(this);
  12093. this._cache.localMatrixUpdated = false;
  12094. this._cache.position = BABYLON.Vector3.Zero();
  12095. this._cache.scaling = BABYLON.Vector3.Zero();
  12096. this._cache.rotation = BABYLON.Vector3.Zero();
  12097. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12098. this._cache.billboardMode = -1;
  12099. };
  12100. AbstractMesh.prototype.markAsDirty = function (property) {
  12101. if (property === "rotation") {
  12102. this.rotationQuaternion = null;
  12103. }
  12104. this._currentRenderId = Number.MAX_VALUE;
  12105. this._isDirty = true;
  12106. return this;
  12107. };
  12108. /**
  12109. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12110. * Returns the AbstractMesh.
  12111. */
  12112. AbstractMesh.prototype._updateBoundingInfo = function () {
  12113. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12114. this._boundingInfo.update(this.worldMatrixFromCache);
  12115. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12116. return this;
  12117. };
  12118. /**
  12119. * Update a mesh's children BoundingInfo objects only.
  12120. * Returns the AbstractMesh.
  12121. */
  12122. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  12123. if (!this.subMeshes) {
  12124. return;
  12125. }
  12126. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  12127. var subMesh = this.subMeshes[subIndex];
  12128. if (!subMesh.IsGlobal) {
  12129. subMesh.updateBoundingInfo(matrix);
  12130. }
  12131. }
  12132. return this;
  12133. };
  12134. /**
  12135. * Computes the mesh World matrix and returns it.
  12136. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  12137. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  12138. * If the parameter `force`is set to `true`, the actual computation is done.
  12139. * Returns the mesh World Matrix.
  12140. */
  12141. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  12142. if (this._isWorldMatrixFrozen) {
  12143. return this._worldMatrix;
  12144. }
  12145. if (!force && this.isSynchronized(true)) {
  12146. this._currentRenderId = this.getScene().getRenderId();
  12147. return this._worldMatrix;
  12148. }
  12149. this._cache.position.copyFrom(this.position);
  12150. this._cache.scaling.copyFrom(this.scaling);
  12151. this._cache.pivotMatrixUpdated = false;
  12152. this._cache.billboardMode = this.billboardMode;
  12153. this._currentRenderId = this.getScene().getRenderId();
  12154. this._isDirty = false;
  12155. // Scaling
  12156. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  12157. // Rotation
  12158. //rotate, if quaternion is set and rotation was used
  12159. if (this.rotationQuaternion) {
  12160. var len = this.rotation.length();
  12161. if (len) {
  12162. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  12163. this.rotation.copyFromFloats(0, 0, 0);
  12164. }
  12165. }
  12166. if (this.rotationQuaternion) {
  12167. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  12168. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  12169. }
  12170. else {
  12171. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  12172. this._cache.rotation.copyFrom(this.rotation);
  12173. }
  12174. // Translation
  12175. if (this.infiniteDistance && !this.parent) {
  12176. var camera = this.getScene().activeCamera;
  12177. if (camera) {
  12178. var cameraWorldMatrix = camera.getWorldMatrix();
  12179. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  12180. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  12181. }
  12182. }
  12183. else {
  12184. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  12185. }
  12186. // Composing transformations
  12187. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  12188. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12189. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  12190. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  12191. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  12192. // Need to decompose each rotation here
  12193. var currentPosition = BABYLON.Tmp.Vector3[3];
  12194. if (this.parent && this.parent.getWorldMatrix) {
  12195. if (this._meshToBoneReferal) {
  12196. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12197. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  12198. }
  12199. else {
  12200. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  12201. }
  12202. }
  12203. else {
  12204. currentPosition.copyFrom(this.position);
  12205. }
  12206. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  12207. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  12208. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  12209. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  12210. }
  12211. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  12212. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  12213. }
  12214. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  12215. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  12216. }
  12217. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  12218. }
  12219. else {
  12220. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  12221. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  12222. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  12223. }
  12224. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  12225. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  12226. }
  12227. // Local world
  12228. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  12229. // Parent
  12230. if (this.parent && this.parent.getWorldMatrix) {
  12231. this._markSyncedWithParent();
  12232. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  12233. if (this._meshToBoneReferal) {
  12234. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12235. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  12236. }
  12237. else {
  12238. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  12239. }
  12240. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  12241. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  12242. this._worldMatrix.copyFrom(this._localWorld);
  12243. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  12244. }
  12245. else {
  12246. if (this._meshToBoneReferal) {
  12247. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  12248. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  12249. }
  12250. else {
  12251. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  12252. }
  12253. }
  12254. }
  12255. else {
  12256. this._worldMatrix.copyFrom(this._localWorld);
  12257. }
  12258. // Bounding info
  12259. this._updateBoundingInfo();
  12260. // Absolute position
  12261. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  12262. // Callbacks
  12263. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  12264. if (!this._poseMatrix) {
  12265. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  12266. }
  12267. return this._worldMatrix;
  12268. };
  12269. /**
  12270. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  12271. * @param func: callback function to add
  12272. *
  12273. * Returns the AbstractMesh.
  12274. */
  12275. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  12276. this.onAfterWorldMatrixUpdateObservable.add(func);
  12277. return this;
  12278. };
  12279. /**
  12280. * Removes a registered callback function.
  12281. * Returns the AbstractMesh.
  12282. */
  12283. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  12284. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  12285. return this;
  12286. };
  12287. /**
  12288. * Sets the mesh position in its local space.
  12289. * Returns the AbstractMesh.
  12290. */
  12291. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  12292. this.computeWorldMatrix();
  12293. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  12294. return this;
  12295. };
  12296. /**
  12297. * Returns the mesh position in the local space from the current World matrix values.
  12298. * Returns a new Vector3.
  12299. */
  12300. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  12301. this.computeWorldMatrix();
  12302. var invLocalWorldMatrix = this._localWorld.clone();
  12303. invLocalWorldMatrix.invert();
  12304. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  12305. };
  12306. /**
  12307. * Translates the mesh along the passed Vector3 in its local space.
  12308. * Returns the AbstractMesh.
  12309. */
  12310. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  12311. this.computeWorldMatrix(true);
  12312. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  12313. return this;
  12314. };
  12315. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  12316. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  12317. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  12318. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  12319. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  12320. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  12321. /// <returns>Mesh oriented towards targetMesh</returns>
  12322. if (yawCor === void 0) { yawCor = 0; }
  12323. if (pitchCor === void 0) { pitchCor = 0; }
  12324. if (rollCor === void 0) { rollCor = 0; }
  12325. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12326. var dv = AbstractMesh._lookAtVectorCache;
  12327. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  12328. targetPoint.subtractToRef(pos, dv);
  12329. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  12330. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  12331. var pitch = Math.atan2(dv.y, len);
  12332. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  12333. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  12334. return this;
  12335. };
  12336. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  12337. this._meshToBoneReferal = affectedMesh;
  12338. this.parent = bone;
  12339. if (bone.getWorldMatrix().determinant() < 0) {
  12340. this.scalingDeterminant *= -1;
  12341. }
  12342. return this;
  12343. };
  12344. AbstractMesh.prototype.detachFromBone = function () {
  12345. if (this.parent.getWorldMatrix().determinant() < 0) {
  12346. this.scalingDeterminant *= -1;
  12347. }
  12348. this._meshToBoneReferal = null;
  12349. this.parent = null;
  12350. return this;
  12351. };
  12352. /**
  12353. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  12354. * A mesh is in the frustum if its bounding box intersects the frustum.
  12355. * Boolean returned.
  12356. */
  12357. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  12358. return this._boundingInfo.isInFrustum(frustumPlanes);
  12359. };
  12360. /**
  12361. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  12362. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  12363. * Boolean returned.
  12364. */
  12365. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12366. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  12367. ;
  12368. };
  12369. /**
  12370. * True if the mesh intersects another mesh or a SolidParticle object.
  12371. * 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)
  12372. * Returns a boolean.
  12373. */
  12374. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  12375. if (!this._boundingInfo || !mesh._boundingInfo) {
  12376. return false;
  12377. }
  12378. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  12379. };
  12380. /**
  12381. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  12382. * Returns a boolean.
  12383. */
  12384. AbstractMesh.prototype.intersectsPoint = function (point) {
  12385. if (!this._boundingInfo) {
  12386. return false;
  12387. }
  12388. return this._boundingInfo.intersectsPoint(point);
  12389. };
  12390. AbstractMesh.prototype.getPhysicsImpostor = function () {
  12391. return this.physicsImpostor;
  12392. };
  12393. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  12394. if (!camera) {
  12395. camera = this.getScene().activeCamera;
  12396. }
  12397. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  12398. };
  12399. /**
  12400. * Returns the distance from the mesh to the active camera.
  12401. * Returns a float.
  12402. */
  12403. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  12404. if (!camera) {
  12405. camera = this.getScene().activeCamera;
  12406. }
  12407. return this.absolutePosition.subtract(camera.position).length();
  12408. };
  12409. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  12410. if (!this.physicsImpostor) {
  12411. return;
  12412. }
  12413. this.physicsImpostor.applyImpulse(force, contactPoint);
  12414. return this;
  12415. };
  12416. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  12417. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  12418. return;
  12419. }
  12420. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  12421. mainPivot: pivot1,
  12422. connectedPivot: pivot2,
  12423. nativeParams: options
  12424. });
  12425. return this;
  12426. };
  12427. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  12428. // Collisions
  12429. /**
  12430. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  12431. * Default `false`.
  12432. */
  12433. get: function () {
  12434. return this._checkCollisions;
  12435. },
  12436. set: function (collisionEnabled) {
  12437. this._checkCollisions = collisionEnabled;
  12438. if (this.getScene().workerCollisions) {
  12439. this.getScene().collisionCoordinator.onMeshUpdated(this);
  12440. }
  12441. },
  12442. enumerable: true,
  12443. configurable: true
  12444. });
  12445. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  12446. var globalPosition = this.getAbsolutePosition();
  12447. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  12448. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  12449. if (!this._collider) {
  12450. this._collider = new BABYLON.Collider();
  12451. }
  12452. this._collider.radius = this.ellipsoid;
  12453. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  12454. return this;
  12455. };
  12456. // Submeshes octree
  12457. /**
  12458. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  12459. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  12460. * Returns an Octree of submeshes.
  12461. */
  12462. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  12463. if (maxCapacity === void 0) { maxCapacity = 64; }
  12464. if (maxDepth === void 0) { maxDepth = 2; }
  12465. if (!this._submeshesOctree) {
  12466. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  12467. }
  12468. this.computeWorldMatrix(true);
  12469. // Update octree
  12470. var bbox = this.getBoundingInfo().boundingBox;
  12471. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  12472. return this._submeshesOctree;
  12473. };
  12474. // Collisions
  12475. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  12476. this._generatePointsArray();
  12477. // Transformation
  12478. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  12479. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  12480. subMesh._lastColliderWorldVertices = [];
  12481. subMesh._trianglePlanes = [];
  12482. var start = subMesh.verticesStart;
  12483. var end = (subMesh.verticesStart + subMesh.verticesCount);
  12484. for (var i = start; i < end; i++) {
  12485. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  12486. }
  12487. }
  12488. // Collide
  12489. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  12490. if (collider.collisionFound) {
  12491. collider.collidedMesh = this;
  12492. }
  12493. return this;
  12494. };
  12495. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  12496. var subMeshes;
  12497. var len;
  12498. // Octrees
  12499. if (this._submeshesOctree && this.useOctreeForCollisions) {
  12500. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  12501. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  12502. len = intersections.length;
  12503. subMeshes = intersections.data;
  12504. }
  12505. else {
  12506. subMeshes = this.subMeshes;
  12507. len = subMeshes.length;
  12508. }
  12509. for (var index = 0; index < len; index++) {
  12510. var subMesh = subMeshes[index];
  12511. // Bounding test
  12512. if (len > 1 && !subMesh._checkCollision(collider))
  12513. continue;
  12514. this._collideForSubMesh(subMesh, transformMatrix, collider);
  12515. }
  12516. return this;
  12517. };
  12518. AbstractMesh.prototype._checkCollision = function (collider) {
  12519. // Bounding box test
  12520. if (!this._boundingInfo._checkCollision(collider))
  12521. return this;
  12522. // Transformation matrix
  12523. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  12524. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  12525. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  12526. return this;
  12527. };
  12528. // Picking
  12529. AbstractMesh.prototype._generatePointsArray = function () {
  12530. return false;
  12531. };
  12532. /**
  12533. * Checks if the passed Ray intersects with the mesh.
  12534. * Returns an object PickingInfo.
  12535. */
  12536. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  12537. var pickingInfo = new BABYLON.PickingInfo();
  12538. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  12539. return pickingInfo;
  12540. }
  12541. if (!this._generatePointsArray()) {
  12542. return pickingInfo;
  12543. }
  12544. var intersectInfo = null;
  12545. // Octrees
  12546. var subMeshes;
  12547. var len;
  12548. if (this._submeshesOctree && this.useOctreeForPicking) {
  12549. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  12550. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  12551. len = intersections.length;
  12552. subMeshes = intersections.data;
  12553. }
  12554. else {
  12555. subMeshes = this.subMeshes;
  12556. len = subMeshes.length;
  12557. }
  12558. for (var index = 0; index < len; index++) {
  12559. var subMesh = subMeshes[index];
  12560. // Bounding test
  12561. if (len > 1 && !subMesh.canIntersects(ray))
  12562. continue;
  12563. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  12564. if (currentIntersectInfo) {
  12565. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12566. intersectInfo = currentIntersectInfo;
  12567. intersectInfo.subMeshId = index;
  12568. if (fastCheck) {
  12569. break;
  12570. }
  12571. }
  12572. }
  12573. }
  12574. if (intersectInfo) {
  12575. // Get picked point
  12576. var world = this.getWorldMatrix();
  12577. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  12578. var direction = ray.direction.clone();
  12579. direction = direction.scale(intersectInfo.distance);
  12580. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  12581. var pickedPoint = worldOrigin.add(worldDirection);
  12582. // Return result
  12583. pickingInfo.hit = true;
  12584. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  12585. pickingInfo.pickedPoint = pickedPoint;
  12586. pickingInfo.pickedMesh = this;
  12587. pickingInfo.bu = intersectInfo.bu;
  12588. pickingInfo.bv = intersectInfo.bv;
  12589. pickingInfo.faceId = intersectInfo.faceId;
  12590. pickingInfo.subMeshId = intersectInfo.subMeshId;
  12591. return pickingInfo;
  12592. }
  12593. return pickingInfo;
  12594. };
  12595. /**
  12596. * Clones the mesh, used by the class Mesh.
  12597. * Just returns `null` for an AbstractMesh.
  12598. */
  12599. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12600. return null;
  12601. };
  12602. /**
  12603. * Disposes all the mesh submeshes.
  12604. * Returns the AbstractMesh.
  12605. */
  12606. AbstractMesh.prototype.releaseSubMeshes = function () {
  12607. if (this.subMeshes) {
  12608. while (this.subMeshes.length) {
  12609. this.subMeshes[0].dispose();
  12610. }
  12611. }
  12612. else {
  12613. this.subMeshes = new Array();
  12614. }
  12615. return this;
  12616. };
  12617. /**
  12618. * Disposes the AbstractMesh.
  12619. * Some internal references are kept for further use.
  12620. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  12621. * Returns nothing.
  12622. */
  12623. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  12624. var _this = this;
  12625. var index;
  12626. // Action manager
  12627. if (this.actionManager) {
  12628. this.actionManager.dispose();
  12629. this.actionManager = null;
  12630. }
  12631. // Skeleton
  12632. this.skeleton = null;
  12633. // Animations
  12634. this.getScene().stopAnimation(this);
  12635. // Physics
  12636. if (this.physicsImpostor) {
  12637. this.physicsImpostor.dispose();
  12638. }
  12639. // Intersections in progress
  12640. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  12641. var other = this._intersectionsInProgress[index];
  12642. var pos = other._intersectionsInProgress.indexOf(this);
  12643. other._intersectionsInProgress.splice(pos, 1);
  12644. }
  12645. this._intersectionsInProgress = [];
  12646. // Lights
  12647. var lights = this.getScene().lights;
  12648. lights.forEach(function (light) {
  12649. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  12650. if (meshIndex !== -1) {
  12651. light.includedOnlyMeshes.splice(meshIndex, 1);
  12652. }
  12653. meshIndex = light.excludedMeshes.indexOf(_this);
  12654. if (meshIndex !== -1) {
  12655. light.excludedMeshes.splice(meshIndex, 1);
  12656. }
  12657. // Shadow generators
  12658. var generator = light.getShadowGenerator();
  12659. if (generator) {
  12660. var shadowMap = generator.getShadowMap();
  12661. meshIndex = shadowMap.renderList.indexOf(_this);
  12662. if (meshIndex !== -1) {
  12663. shadowMap.renderList.splice(meshIndex, 1);
  12664. }
  12665. }
  12666. });
  12667. // Edges
  12668. if (this._edgesRenderer) {
  12669. this._edgesRenderer.dispose();
  12670. this._edgesRenderer = null;
  12671. }
  12672. // SubMeshes
  12673. if (this.getClassName() !== "InstancedMesh") {
  12674. this.releaseSubMeshes();
  12675. }
  12676. // Octree
  12677. var sceneOctree = this.getScene().selectionOctree;
  12678. if (sceneOctree) {
  12679. var index = sceneOctree.dynamicContent.indexOf(this);
  12680. if (index !== -1) {
  12681. sceneOctree.dynamicContent.splice(index, 1);
  12682. }
  12683. }
  12684. // Engine
  12685. this.getScene().getEngine().wipeCaches();
  12686. // Remove from scene
  12687. this.getScene().removeMesh(this);
  12688. if (!doNotRecurse) {
  12689. // Particles
  12690. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  12691. if (this.getScene().particleSystems[index].emitter === this) {
  12692. this.getScene().particleSystems[index].dispose();
  12693. index--;
  12694. }
  12695. }
  12696. // Children
  12697. var objects = this.getDescendants(true);
  12698. for (index = 0; index < objects.length; index++) {
  12699. objects[index].dispose();
  12700. }
  12701. }
  12702. else {
  12703. var childMeshes = this.getChildMeshes(true);
  12704. for (index = 0; index < childMeshes.length; index++) {
  12705. var child = childMeshes[index];
  12706. child.parent = null;
  12707. child.computeWorldMatrix(true);
  12708. }
  12709. }
  12710. // facet data
  12711. if (this._facetDataEnabled) {
  12712. this.disableFacetData();
  12713. }
  12714. this.onAfterWorldMatrixUpdateObservable.clear();
  12715. this.onCollideObservable.clear();
  12716. this.onCollisionPositionChangeObservable.clear();
  12717. this._isDisposed = true;
  12718. _super.prototype.dispose.call(this);
  12719. };
  12720. /**
  12721. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  12722. * This Vector3 is expressed in the World space.
  12723. */
  12724. AbstractMesh.prototype.getDirection = function (localAxis) {
  12725. var result = BABYLON.Vector3.Zero();
  12726. this.getDirectionToRef(localAxis, result);
  12727. return result;
  12728. };
  12729. /**
  12730. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  12731. * localAxis is expressed in the mesh local space.
  12732. * result is computed in the Wordl space from the mesh World matrix.
  12733. * Returns the AbstractMesh.
  12734. */
  12735. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  12736. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  12737. return this;
  12738. };
  12739. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  12740. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12741. if (this.getScene().getRenderId() == 0) {
  12742. this.computeWorldMatrix(true);
  12743. }
  12744. var wm = this.getWorldMatrix();
  12745. if (space == BABYLON.Space.WORLD) {
  12746. var tmat = BABYLON.Tmp.Matrix[0];
  12747. wm.invertToRef(tmat);
  12748. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  12749. }
  12750. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  12751. this._pivotMatrix.m[12] = -point.x;
  12752. this._pivotMatrix.m[13] = -point.y;
  12753. this._pivotMatrix.m[14] = -point.z;
  12754. this._cache.pivotMatrixUpdated = true;
  12755. return this;
  12756. };
  12757. /**
  12758. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  12759. */
  12760. AbstractMesh.prototype.getPivotPoint = function () {
  12761. var point = BABYLON.Vector3.Zero();
  12762. this.getPivotPointToRef(point);
  12763. return point;
  12764. };
  12765. /**
  12766. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  12767. * Returns the AbstractMesh.
  12768. */
  12769. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  12770. result.x = -this._pivotMatrix.m[12];
  12771. result.y = -this._pivotMatrix.m[13];
  12772. result.z = -this._pivotMatrix.m[14];
  12773. return this;
  12774. };
  12775. /**
  12776. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  12777. */
  12778. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  12779. var point = BABYLON.Vector3.Zero();
  12780. this.getAbsolutePivotPointToRef(point);
  12781. return point;
  12782. };
  12783. /**
  12784. * Defines the passed mesh as the parent of the current mesh.
  12785. * Returns the AbstractMesh.
  12786. */
  12787. AbstractMesh.prototype.setParent = function (mesh) {
  12788. var child = this;
  12789. var parent = mesh;
  12790. if (mesh == null) {
  12791. var rotation = BABYLON.Tmp.Quaternion[0];
  12792. var position = BABYLON.Tmp.Vector3[0];
  12793. var scale = BABYLON.Tmp.Vector3[1];
  12794. child.getWorldMatrix().decompose(scale, rotation, position);
  12795. if (child.rotationQuaternion) {
  12796. child.rotationQuaternion.copyFrom(rotation);
  12797. }
  12798. else {
  12799. rotation.toEulerAnglesToRef(child.rotation);
  12800. }
  12801. child.position.x = position.x;
  12802. child.position.y = position.y;
  12803. child.position.z = position.z;
  12804. }
  12805. else {
  12806. var rotation = BABYLON.Tmp.Quaternion[0];
  12807. var position = BABYLON.Tmp.Vector3[0];
  12808. var scale = BABYLON.Tmp.Vector3[1];
  12809. var m1 = BABYLON.Tmp.Matrix[0];
  12810. var m2 = BABYLON.Tmp.Matrix[1];
  12811. parent.getWorldMatrix().decompose(scale, rotation, position);
  12812. rotation.toRotationMatrix(m1);
  12813. m2.setTranslation(position);
  12814. m2.multiplyToRef(m1, m1);
  12815. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  12816. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12817. m.decompose(scale, rotation, position);
  12818. if (child.rotationQuaternion) {
  12819. child.rotationQuaternion.copyFrom(rotation);
  12820. }
  12821. else {
  12822. rotation.toEulerAnglesToRef(child.rotation);
  12823. }
  12824. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  12825. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12826. m.decompose(scale, rotation, position);
  12827. child.position.x = position.x;
  12828. child.position.y = position.y;
  12829. child.position.z = position.z;
  12830. }
  12831. child.parent = parent;
  12832. return this;
  12833. };
  12834. /**
  12835. * Adds the passed mesh as a child to the current mesh.
  12836. * Returns the AbstractMesh.
  12837. */
  12838. AbstractMesh.prototype.addChild = function (mesh) {
  12839. mesh.setParent(this);
  12840. return this;
  12841. };
  12842. /**
  12843. * Removes the passed mesh from the current mesh children list.
  12844. * Returns the AbstractMesh.
  12845. */
  12846. AbstractMesh.prototype.removeChild = function (mesh) {
  12847. mesh.setParent(null);
  12848. return this;
  12849. };
  12850. /**
  12851. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  12852. * Returns the AbstractMesh.
  12853. */
  12854. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  12855. result.x = this._pivotMatrix.m[12];
  12856. result.y = this._pivotMatrix.m[13];
  12857. result.z = this._pivotMatrix.m[14];
  12858. this.getPivotPointToRef(result);
  12859. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  12860. return this;
  12861. };
  12862. // Facet data
  12863. /**
  12864. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  12865. * Returns the AbstractMesh.
  12866. */
  12867. AbstractMesh.prototype._initFacetData = function () {
  12868. if (!this._facetNormals) {
  12869. this._facetNormals = new Array();
  12870. }
  12871. if (!this._facetPositions) {
  12872. this._facetPositions = new Array();
  12873. }
  12874. if (!this._facetPartitioning) {
  12875. this._facetPartitioning = new Array();
  12876. }
  12877. this._facetNb = this.getIndices().length / 3;
  12878. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  12879. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  12880. for (var f = 0; f < this._facetNb; f++) {
  12881. this._facetNormals[f] = BABYLON.Vector3.Zero();
  12882. this._facetPositions[f] = BABYLON.Vector3.Zero();
  12883. }
  12884. this._facetDataEnabled = true;
  12885. return this;
  12886. };
  12887. /**
  12888. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  12889. * This method can be called within the render loop.
  12890. * 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.
  12891. * Returns the AbstractMesh.
  12892. */
  12893. AbstractMesh.prototype.updateFacetData = function () {
  12894. if (!this._facetDataEnabled) {
  12895. this._initFacetData();
  12896. }
  12897. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12898. var indices = this.getIndices();
  12899. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12900. var bInfo = this.getBoundingInfo();
  12901. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  12902. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  12903. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  12904. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  12905. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  12906. this._subDiv.max = this._partitioningSubdivisions;
  12907. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  12908. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  12909. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  12910. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  12911. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  12912. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  12913. // set the parameters for ComputeNormals()
  12914. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  12915. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  12916. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  12917. this._facetParameters.bInfo = bInfo;
  12918. this._facetParameters.bbSize = this._bbSize;
  12919. this._facetParameters.subDiv = this._subDiv;
  12920. this._facetParameters.ratio = this.partitioningBBoxRatio;
  12921. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  12922. return this;
  12923. };
  12924. /**
  12925. * Returns the facetLocalNormals array.
  12926. * The normals are expressed in the mesh local space.
  12927. */
  12928. AbstractMesh.prototype.getFacetLocalNormals = function () {
  12929. if (!this._facetNormals) {
  12930. this.updateFacetData();
  12931. }
  12932. return this._facetNormals;
  12933. };
  12934. /**
  12935. * Returns the facetLocalPositions array.
  12936. * The facet positions are expressed in the mesh local space.
  12937. */
  12938. AbstractMesh.prototype.getFacetLocalPositions = function () {
  12939. if (!this._facetPositions) {
  12940. this.updateFacetData();
  12941. }
  12942. return this._facetPositions;
  12943. };
  12944. /**
  12945. * Returns the facetLocalPartioning array.
  12946. */
  12947. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  12948. if (!this._facetPartitioning) {
  12949. this.updateFacetData();
  12950. }
  12951. return this._facetPartitioning;
  12952. };
  12953. /**
  12954. * Returns the i-th facet position in the world system.
  12955. * This method allocates a new Vector3 per call.
  12956. */
  12957. AbstractMesh.prototype.getFacetPosition = function (i) {
  12958. var pos = BABYLON.Vector3.Zero();
  12959. this.getFacetPositionToRef(i, pos);
  12960. return pos;
  12961. };
  12962. /**
  12963. * Sets the reference Vector3 with the i-th facet position in the world system.
  12964. * Returns the AbstractMesh.
  12965. */
  12966. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  12967. var localPos = (this.getFacetLocalPositions())[i];
  12968. var world = this.getWorldMatrix();
  12969. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  12970. return this;
  12971. };
  12972. /**
  12973. * Returns the i-th facet normal in the world system.
  12974. * This method allocates a new Vector3 per call.
  12975. */
  12976. AbstractMesh.prototype.getFacetNormal = function (i) {
  12977. var norm = BABYLON.Vector3.Zero();
  12978. this.getFacetNormalToRef(i, norm);
  12979. return norm;
  12980. };
  12981. /**
  12982. * Sets the reference Vector3 with the i-th facet normal in the world system.
  12983. * Returns the AbstractMesh.
  12984. */
  12985. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  12986. var localNorm = (this.getFacetLocalNormals())[i];
  12987. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  12988. return this;
  12989. };
  12990. /**
  12991. * 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).
  12992. */
  12993. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  12994. var bInfo = this.getBoundingInfo();
  12995. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  12996. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  12997. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  12998. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  12999. return null;
  13000. }
  13001. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  13002. };
  13003. /**
  13004. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  13005. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  13006. * 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.
  13007. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13008. * 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.
  13009. */
  13010. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  13011. if (checkFace === void 0) { checkFace = false; }
  13012. if (facing === void 0) { facing = true; }
  13013. var world = this.getWorldMatrix();
  13014. var invMat = BABYLON.Tmp.Matrix[5];
  13015. world.invertToRef(invMat);
  13016. var invVect = BABYLON.Tmp.Vector3[8];
  13017. var closest = null;
  13018. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  13019. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  13020. if (projected) {
  13021. // tranform the local computed projected vector to world coordinates
  13022. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  13023. }
  13024. return closest;
  13025. };
  13026. /**
  13027. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  13028. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  13029. * 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.
  13030. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13031. * 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.
  13032. */
  13033. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  13034. if (checkFace === void 0) { checkFace = false; }
  13035. if (facing === void 0) { facing = true; }
  13036. var closest = null;
  13037. var tmpx = 0.0;
  13038. var tmpy = 0.0;
  13039. var tmpz = 0.0;
  13040. var d = 0.0; // tmp dot facet normal * facet position
  13041. var t0 = 0.0;
  13042. var projx = 0.0;
  13043. var projy = 0.0;
  13044. var projz = 0.0;
  13045. // Get all the facets in the same partitioning block than (x, y, z)
  13046. var facetPositions = this.getFacetLocalPositions();
  13047. var facetNormals = this.getFacetLocalNormals();
  13048. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  13049. if (!facetsInBlock) {
  13050. return null;
  13051. }
  13052. // Get the closest facet to (x, y, z)
  13053. var shortest = Number.MAX_VALUE; // init distance vars
  13054. var tmpDistance = shortest;
  13055. var fib; // current facet in the block
  13056. var norm; // current facet normal
  13057. var p0; // current facet barycenter position
  13058. // loop on all the facets in the current partitioning block
  13059. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  13060. fib = facetsInBlock[idx];
  13061. norm = facetNormals[fib];
  13062. p0 = facetPositions[fib];
  13063. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  13064. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  13065. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  13066. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  13067. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  13068. projx = x + norm.x * t0;
  13069. projy = y + norm.y * t0;
  13070. projz = z + norm.z * t0;
  13071. tmpx = projx - x;
  13072. tmpy = projy - y;
  13073. tmpz = projz - z;
  13074. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13075. if (tmpDistance < shortest) {
  13076. shortest = tmpDistance;
  13077. closest = fib;
  13078. if (projected) {
  13079. projected.x = projx;
  13080. projected.y = projy;
  13081. projected.z = projz;
  13082. }
  13083. }
  13084. }
  13085. }
  13086. return closest;
  13087. };
  13088. /**
  13089. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13090. */
  13091. AbstractMesh.prototype.getFacetDataParameters = function () {
  13092. return this._facetParameters;
  13093. };
  13094. /**
  13095. * Disables the feature FacetData and frees the related memory.
  13096. * Returns the AbstractMesh.
  13097. */
  13098. AbstractMesh.prototype.disableFacetData = function () {
  13099. if (this._facetDataEnabled) {
  13100. this._facetDataEnabled = false;
  13101. this._facetPositions = null;
  13102. this._facetNormals = null;
  13103. this._facetPartitioning = null;
  13104. this._facetParameters = null;
  13105. }
  13106. return this;
  13107. };
  13108. /**
  13109. * Creates new normals data for the mesh.
  13110. * @param updatable.
  13111. */
  13112. AbstractMesh.prototype.createNormals = function (updatable) {
  13113. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13114. var indices = this.getIndices();
  13115. var normals;
  13116. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13117. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13118. }
  13119. else {
  13120. normals = [];
  13121. }
  13122. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  13123. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  13124. };
  13125. return AbstractMesh;
  13126. }(BABYLON.Node));
  13127. // Statics
  13128. AbstractMesh._BILLBOARDMODE_NONE = 0;
  13129. AbstractMesh._BILLBOARDMODE_X = 1;
  13130. AbstractMesh._BILLBOARDMODE_Y = 2;
  13131. AbstractMesh._BILLBOARDMODE_Z = 4;
  13132. AbstractMesh._BILLBOARDMODE_ALL = 7;
  13133. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  13134. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  13135. BABYLON.AbstractMesh = AbstractMesh;
  13136. })(BABYLON || (BABYLON = {}));
  13137. //# sourceMappingURL=babylon.abstractMesh.js.map
  13138. var BABYLON;
  13139. (function (BABYLON) {
  13140. var Light = (function (_super) {
  13141. __extends(Light, _super);
  13142. /**
  13143. * Creates a Light object in the scene.
  13144. * Documentation : http://doc.babylonjs.com/tutorials/lights
  13145. */
  13146. function Light(name, scene) {
  13147. var _this = _super.call(this, name, scene) || this;
  13148. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  13149. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  13150. _this.intensity = 1.0;
  13151. _this.range = Number.MAX_VALUE;
  13152. /**
  13153. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  13154. * of light.
  13155. */
  13156. _this._photometricScale = 1.0;
  13157. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  13158. _this._radius = 0.00001;
  13159. _this.renderPriority = 0;
  13160. /**
  13161. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  13162. * the current shadow generator.
  13163. */
  13164. _this.shadowEnabled = true;
  13165. _this._excludeWithLayerMask = 0;
  13166. _this._includeOnlyWithLayerMask = 0;
  13167. _this._lightmapMode = 0;
  13168. _this._excludedMeshesIds = new Array();
  13169. _this._includedOnlyMeshesIds = new Array();
  13170. _this.getScene().addLight(_this);
  13171. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  13172. _this._buildUniformLayout();
  13173. _this.includedOnlyMeshes = new Array();
  13174. _this.excludedMeshes = new Array();
  13175. _this._resyncMeshes();
  13176. return _this;
  13177. }
  13178. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  13179. /**
  13180. * If every light affecting the material is in this lightmapMode,
  13181. * material.lightmapTexture adds or multiplies
  13182. * (depends on material.useLightmapAsShadowmap)
  13183. * after every other light calculations.
  13184. */
  13185. get: function () {
  13186. return Light._LIGHTMAP_DEFAULT;
  13187. },
  13188. enumerable: true,
  13189. configurable: true
  13190. });
  13191. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  13192. /**
  13193. * material.lightmapTexture as only diffuse lighting from this light
  13194. * adds pnly specular lighting from this light
  13195. * adds dynamic shadows
  13196. */
  13197. get: function () {
  13198. return Light._LIGHTMAP_SPECULAR;
  13199. },
  13200. enumerable: true,
  13201. configurable: true
  13202. });
  13203. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  13204. /**
  13205. * material.lightmapTexture as only lighting
  13206. * no light calculation from this light
  13207. * only adds dynamic shadows from this light
  13208. */
  13209. get: function () {
  13210. return Light._LIGHTMAP_SHADOWSONLY;
  13211. },
  13212. enumerable: true,
  13213. configurable: true
  13214. });
  13215. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  13216. /**
  13217. * Each light type uses the default quantity according to its type:
  13218. * point/spot lights use luminous intensity
  13219. * directional lights use illuminance
  13220. */
  13221. get: function () {
  13222. return Light._INTENSITYMODE_AUTOMATIC;
  13223. },
  13224. enumerable: true,
  13225. configurable: true
  13226. });
  13227. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  13228. /**
  13229. * lumen (lm)
  13230. */
  13231. get: function () {
  13232. return Light._INTENSITYMODE_LUMINOUSPOWER;
  13233. },
  13234. enumerable: true,
  13235. configurable: true
  13236. });
  13237. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  13238. /**
  13239. * candela (lm/sr)
  13240. */
  13241. get: function () {
  13242. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  13243. },
  13244. enumerable: true,
  13245. configurable: true
  13246. });
  13247. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  13248. /**
  13249. * lux (lm/m^2)
  13250. */
  13251. get: function () {
  13252. return Light._INTENSITYMODE_ILLUMINANCE;
  13253. },
  13254. enumerable: true,
  13255. configurable: true
  13256. });
  13257. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  13258. /**
  13259. * nit (cd/m^2)
  13260. */
  13261. get: function () {
  13262. return Light._INTENSITYMODE_LUMINANCE;
  13263. },
  13264. enumerable: true,
  13265. configurable: true
  13266. });
  13267. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  13268. /**
  13269. * Light type const id of the point light.
  13270. */
  13271. get: function () {
  13272. return Light._LIGHTTYPEID_POINTLIGHT;
  13273. },
  13274. enumerable: true,
  13275. configurable: true
  13276. });
  13277. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  13278. /**
  13279. * Light type const id of the directional light.
  13280. */
  13281. get: function () {
  13282. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  13283. },
  13284. enumerable: true,
  13285. configurable: true
  13286. });
  13287. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  13288. /**
  13289. * Light type const id of the spot light.
  13290. */
  13291. get: function () {
  13292. return Light._LIGHTTYPEID_SPOTLIGHT;
  13293. },
  13294. enumerable: true,
  13295. configurable: true
  13296. });
  13297. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  13298. /**
  13299. * Light type const id of the hemispheric light.
  13300. */
  13301. get: function () {
  13302. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  13303. },
  13304. enumerable: true,
  13305. configurable: true
  13306. });
  13307. Object.defineProperty(Light.prototype, "intensityMode", {
  13308. /**
  13309. * Gets the photometric scale used to interpret the intensity.
  13310. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13311. */
  13312. get: function () {
  13313. return this._intensityMode;
  13314. },
  13315. /**
  13316. * Sets the photometric scale used to interpret the intensity.
  13317. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  13318. */
  13319. set: function (value) {
  13320. this._intensityMode = value;
  13321. this._computePhotometricScale();
  13322. },
  13323. enumerable: true,
  13324. configurable: true
  13325. });
  13326. ;
  13327. ;
  13328. Object.defineProperty(Light.prototype, "radius", {
  13329. /**
  13330. * Gets the light radius used by PBR Materials to simulate soft area lights.
  13331. */
  13332. get: function () {
  13333. return this._radius;
  13334. },
  13335. /**
  13336. * sets the light radius used by PBR Materials to simulate soft area lights.
  13337. */
  13338. set: function (value) {
  13339. this._radius = value;
  13340. this._computePhotometricScale();
  13341. },
  13342. enumerable: true,
  13343. configurable: true
  13344. });
  13345. ;
  13346. ;
  13347. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  13348. get: function () {
  13349. return this._includedOnlyMeshes;
  13350. },
  13351. set: function (value) {
  13352. this._includedOnlyMeshes = value;
  13353. this._hookArrayForIncludedOnly(value);
  13354. },
  13355. enumerable: true,
  13356. configurable: true
  13357. });
  13358. Object.defineProperty(Light.prototype, "excludedMeshes", {
  13359. get: function () {
  13360. return this._excludedMeshes;
  13361. },
  13362. set: function (value) {
  13363. this._excludedMeshes = value;
  13364. this._hookArrayForExcluded(value);
  13365. },
  13366. enumerable: true,
  13367. configurable: true
  13368. });
  13369. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  13370. get: function () {
  13371. return this._excludeWithLayerMask;
  13372. },
  13373. set: function (value) {
  13374. this._excludeWithLayerMask = value;
  13375. this._resyncMeshes();
  13376. },
  13377. enumerable: true,
  13378. configurable: true
  13379. });
  13380. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  13381. get: function () {
  13382. return this._includeOnlyWithLayerMask;
  13383. },
  13384. set: function (value) {
  13385. this._includeOnlyWithLayerMask = value;
  13386. this._resyncMeshes();
  13387. },
  13388. enumerable: true,
  13389. configurable: true
  13390. });
  13391. Object.defineProperty(Light.prototype, "lightmapMode", {
  13392. get: function () {
  13393. return this._lightmapMode;
  13394. },
  13395. set: function (value) {
  13396. if (this._lightmapMode === value) {
  13397. return;
  13398. }
  13399. this._lightmapMode = value;
  13400. this._markMeshesAsLightDirty();
  13401. },
  13402. enumerable: true,
  13403. configurable: true
  13404. });
  13405. Light.prototype._buildUniformLayout = function () {
  13406. // Overridden
  13407. };
  13408. /**
  13409. * Returns the string "Light".
  13410. */
  13411. Light.prototype.getClassName = function () {
  13412. return "Light";
  13413. };
  13414. /**
  13415. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13416. */
  13417. Light.prototype.toString = function (fullDetails) {
  13418. var ret = "Name: " + this.name;
  13419. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  13420. if (this.animations) {
  13421. for (var i = 0; i < this.animations.length; i++) {
  13422. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13423. }
  13424. }
  13425. if (fullDetails) {
  13426. }
  13427. return ret;
  13428. };
  13429. /**
  13430. * Set the enabled state of this node.
  13431. * @param {boolean} value - the new enabled state
  13432. * @see isEnabled
  13433. */
  13434. Light.prototype.setEnabled = function (value) {
  13435. _super.prototype.setEnabled.call(this, value);
  13436. this._resyncMeshes();
  13437. };
  13438. /**
  13439. * Returns the Light associated shadow generator.
  13440. */
  13441. Light.prototype.getShadowGenerator = function () {
  13442. return this._shadowGenerator;
  13443. };
  13444. /**
  13445. * Returns a Vector3, the absolute light position in the World.
  13446. */
  13447. Light.prototype.getAbsolutePosition = function () {
  13448. return BABYLON.Vector3.Zero();
  13449. };
  13450. Light.prototype.transferToEffect = function (effect, lightIndex) {
  13451. };
  13452. Light.prototype._getWorldMatrix = function () {
  13453. return BABYLON.Matrix.Identity();
  13454. };
  13455. /**
  13456. * Boolean : True if the light will affect the passed mesh.
  13457. */
  13458. Light.prototype.canAffectMesh = function (mesh) {
  13459. if (!mesh) {
  13460. return true;
  13461. }
  13462. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  13463. return false;
  13464. }
  13465. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  13466. return false;
  13467. }
  13468. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  13469. return false;
  13470. }
  13471. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  13472. return false;
  13473. }
  13474. return true;
  13475. };
  13476. /**
  13477. * Returns the light World matrix.
  13478. */
  13479. Light.prototype.getWorldMatrix = function () {
  13480. this._currentRenderId = this.getScene().getRenderId();
  13481. var worldMatrix = this._getWorldMatrix();
  13482. if (this.parent && this.parent.getWorldMatrix) {
  13483. if (!this._parentedWorldMatrix) {
  13484. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  13485. }
  13486. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  13487. this._markSyncedWithParent();
  13488. return this._parentedWorldMatrix;
  13489. }
  13490. return worldMatrix;
  13491. };
  13492. /**
  13493. * Sort function to order lights for rendering.
  13494. * @param a First Light object to compare to second.
  13495. * @param b Second Light object to compare first.
  13496. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  13497. */
  13498. Light.compareLightsPriority = function (a, b) {
  13499. //shadow-casting lights have priority over non-shadow-casting lights
  13500. //the renderPrioirty is a secondary sort criterion
  13501. if (a.shadowEnabled !== b.shadowEnabled) {
  13502. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  13503. }
  13504. return b.renderPriority - a.renderPriority;
  13505. };
  13506. /**
  13507. * Disposes the light.
  13508. */
  13509. Light.prototype.dispose = function () {
  13510. if (this._shadowGenerator) {
  13511. this._shadowGenerator.dispose();
  13512. this._shadowGenerator = null;
  13513. }
  13514. // Animations
  13515. this.getScene().stopAnimation(this);
  13516. // Remove from meshes
  13517. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13518. var mesh = _a[_i];
  13519. mesh._removeLightSource(this);
  13520. }
  13521. this._uniformBuffer.dispose();
  13522. // Remove from scene
  13523. this.getScene().removeLight(this);
  13524. _super.prototype.dispose.call(this);
  13525. };
  13526. /**
  13527. * Returns the light type ID (integer).
  13528. */
  13529. Light.prototype.getTypeID = function () {
  13530. return 0;
  13531. };
  13532. /**
  13533. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  13534. */
  13535. Light.prototype.getScaledIntensity = function () {
  13536. return this._photometricScale * this.intensity;
  13537. };
  13538. /**
  13539. * Returns a new Light object, named "name", from the current one.
  13540. */
  13541. Light.prototype.clone = function (name) {
  13542. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  13543. };
  13544. /**
  13545. * Serializes the current light into a Serialization object.
  13546. * Returns the serialized object.
  13547. */
  13548. Light.prototype.serialize = function () {
  13549. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13550. // Type
  13551. serializationObject.type = this.getTypeID();
  13552. // Parent
  13553. if (this.parent) {
  13554. serializationObject.parentId = this.parent.id;
  13555. }
  13556. // Inclusion / exclusions
  13557. if (this.excludedMeshes.length > 0) {
  13558. serializationObject.excludedMeshesIds = [];
  13559. this.excludedMeshes.forEach(function (mesh) {
  13560. serializationObject.excludedMeshesIds.push(mesh.id);
  13561. });
  13562. }
  13563. if (this.includedOnlyMeshes.length > 0) {
  13564. serializationObject.includedOnlyMeshesIds = [];
  13565. this.includedOnlyMeshes.forEach(function (mesh) {
  13566. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  13567. });
  13568. }
  13569. // Animations
  13570. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13571. serializationObject.ranges = this.serializeAnimationRanges();
  13572. return serializationObject;
  13573. };
  13574. /**
  13575. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  13576. * This new light is named "name" and added to the passed scene.
  13577. */
  13578. Light.GetConstructorFromName = function (type, name, scene) {
  13579. switch (type) {
  13580. case 0:
  13581. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  13582. case 1:
  13583. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  13584. case 2:
  13585. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  13586. case 3:
  13587. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  13588. }
  13589. };
  13590. /**
  13591. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  13592. */
  13593. Light.Parse = function (parsedLight, scene) {
  13594. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  13595. // Inclusion / exclusions
  13596. if (parsedLight.excludedMeshesIds) {
  13597. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  13598. }
  13599. if (parsedLight.includedOnlyMeshesIds) {
  13600. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  13601. }
  13602. // Parent
  13603. if (parsedLight.parentId) {
  13604. light._waitingParentId = parsedLight.parentId;
  13605. }
  13606. // Animations
  13607. if (parsedLight.animations) {
  13608. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  13609. var parsedAnimation = parsedLight.animations[animationIndex];
  13610. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13611. }
  13612. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  13613. }
  13614. if (parsedLight.autoAnimate) {
  13615. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  13616. }
  13617. return light;
  13618. };
  13619. Light.prototype._hookArrayForExcluded = function (array) {
  13620. var _this = this;
  13621. var oldPush = array.push;
  13622. array.push = function () {
  13623. var items = [];
  13624. for (var _i = 0; _i < arguments.length; _i++) {
  13625. items[_i] = arguments[_i];
  13626. }
  13627. var result = oldPush.apply(array, items);
  13628. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  13629. var item = items_1[_a];
  13630. item._resyncLighSource(_this);
  13631. }
  13632. return result;
  13633. };
  13634. var oldSplice = array.splice;
  13635. array.splice = function (index, deleteCount) {
  13636. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13637. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  13638. var item = deleted_1[_i];
  13639. item._resyncLighSource(_this);
  13640. }
  13641. return deleted;
  13642. };
  13643. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  13644. var item = array_1[_i];
  13645. item._resyncLighSource(this);
  13646. }
  13647. };
  13648. Light.prototype._hookArrayForIncludedOnly = function (array) {
  13649. var _this = this;
  13650. var oldPush = array.push;
  13651. array.push = function () {
  13652. var items = [];
  13653. for (var _i = 0; _i < arguments.length; _i++) {
  13654. items[_i] = arguments[_i];
  13655. }
  13656. var result = oldPush.apply(array, items);
  13657. _this._resyncMeshes();
  13658. return result;
  13659. };
  13660. var oldSplice = array.splice;
  13661. array.splice = function (index, deleteCount) {
  13662. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13663. _this._resyncMeshes();
  13664. return deleted;
  13665. };
  13666. this._resyncMeshes();
  13667. };
  13668. Light.prototype._resyncMeshes = function () {
  13669. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13670. var mesh = _a[_i];
  13671. mesh._resyncLighSource(this);
  13672. }
  13673. };
  13674. Light.prototype._markMeshesAsLightDirty = function () {
  13675. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13676. var mesh = _a[_i];
  13677. if (mesh._lightSources.indexOf(this) !== -1) {
  13678. mesh._markSubMeshesAsLightDirty();
  13679. }
  13680. }
  13681. };
  13682. /**
  13683. * Recomputes the cached photometric scale if needed.
  13684. */
  13685. Light.prototype._computePhotometricScale = function () {
  13686. this._photometricScale = this._getPhotometricScale();
  13687. this.getScene().resetCachedMaterial();
  13688. };
  13689. /**
  13690. * Returns the Photometric Scale according to the light type and intensity mode.
  13691. */
  13692. Light.prototype._getPhotometricScale = function () {
  13693. var photometricScale = 0.0;
  13694. var lightTypeID = this.getTypeID();
  13695. //get photometric mode
  13696. var photometricMode = this.intensityMode;
  13697. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  13698. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  13699. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  13700. }
  13701. else {
  13702. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  13703. }
  13704. }
  13705. //compute photometric scale
  13706. switch (lightTypeID) {
  13707. case Light.LIGHTTYPEID_POINTLIGHT:
  13708. case Light.LIGHTTYPEID_SPOTLIGHT:
  13709. switch (photometricMode) {
  13710. case Light.INTENSITYMODE_LUMINOUSPOWER:
  13711. photometricScale = 1.0 / (4.0 * Math.PI);
  13712. break;
  13713. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  13714. photometricScale = 1.0;
  13715. break;
  13716. case Light.INTENSITYMODE_LUMINANCE:
  13717. photometricScale = this.radius * this.radius;
  13718. break;
  13719. }
  13720. break;
  13721. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  13722. switch (photometricMode) {
  13723. case Light.INTENSITYMODE_ILLUMINANCE:
  13724. photometricScale = 1.0;
  13725. break;
  13726. case Light.INTENSITYMODE_LUMINANCE:
  13727. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  13728. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  13729. var apexAngleRadians = this.radius;
  13730. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  13731. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  13732. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  13733. photometricScale = solidAngle;
  13734. break;
  13735. }
  13736. break;
  13737. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  13738. // No fall off in hemisperic light.
  13739. photometricScale = 1.0;
  13740. break;
  13741. }
  13742. return photometricScale;
  13743. };
  13744. Light.prototype._reorderLightsInScene = function () {
  13745. var scene = this.getScene();
  13746. if (this.renderPriority != 0) {
  13747. scene.requireLightSorting = true;
  13748. }
  13749. this.getScene().sortLightsByPriority();
  13750. };
  13751. return Light;
  13752. }(BABYLON.Node));
  13753. //lightmapMode Consts
  13754. Light._LIGHTMAP_DEFAULT = 0;
  13755. Light._LIGHTMAP_SPECULAR = 1;
  13756. Light._LIGHTMAP_SHADOWSONLY = 2;
  13757. // Intensity Mode Consts
  13758. Light._INTENSITYMODE_AUTOMATIC = 0;
  13759. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  13760. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  13761. Light._INTENSITYMODE_ILLUMINANCE = 3;
  13762. Light._INTENSITYMODE_LUMINANCE = 4;
  13763. // Light types ids const.
  13764. Light._LIGHTTYPEID_POINTLIGHT = 0;
  13765. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  13766. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  13767. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  13768. __decorate([
  13769. BABYLON.serializeAsColor3()
  13770. ], Light.prototype, "diffuse", void 0);
  13771. __decorate([
  13772. BABYLON.serializeAsColor3()
  13773. ], Light.prototype, "specular", void 0);
  13774. __decorate([
  13775. BABYLON.serialize()
  13776. ], Light.prototype, "intensity", void 0);
  13777. __decorate([
  13778. BABYLON.serialize()
  13779. ], Light.prototype, "range", void 0);
  13780. __decorate([
  13781. BABYLON.serialize()
  13782. ], Light.prototype, "intensityMode", null);
  13783. __decorate([
  13784. BABYLON.serialize()
  13785. ], Light.prototype, "radius", null);
  13786. __decorate([
  13787. BABYLON.serialize()
  13788. ], Light.prototype, "_renderPriority", void 0);
  13789. __decorate([
  13790. BABYLON.expandToProperty("_reorderLightsInScene")
  13791. ], Light.prototype, "renderPriority", void 0);
  13792. __decorate([
  13793. BABYLON.serialize()
  13794. ], Light.prototype, "shadowEnabled", void 0);
  13795. __decorate([
  13796. BABYLON.serialize("excludeWithLayerMask")
  13797. ], Light.prototype, "_excludeWithLayerMask", void 0);
  13798. __decorate([
  13799. BABYLON.serialize("includeOnlyWithLayerMask")
  13800. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  13801. __decorate([
  13802. BABYLON.serialize("lightmapMode")
  13803. ], Light.prototype, "_lightmapMode", void 0);
  13804. BABYLON.Light = Light;
  13805. })(BABYLON || (BABYLON = {}));
  13806. //# sourceMappingURL=babylon.light.js.map
  13807. var BABYLON;
  13808. (function (BABYLON) {
  13809. var Camera = (function (_super) {
  13810. __extends(Camera, _super);
  13811. function Camera(name, position, scene) {
  13812. var _this = _super.call(this, name, scene) || this;
  13813. _this.upVector = BABYLON.Vector3.Up();
  13814. _this.orthoLeft = null;
  13815. _this.orthoRight = null;
  13816. _this.orthoBottom = null;
  13817. _this.orthoTop = null;
  13818. _this.fov = 0.8;
  13819. _this.minZ = 1.0;
  13820. _this.maxZ = 10000.0;
  13821. _this.inertia = 0.9;
  13822. _this.mode = Camera.PERSPECTIVE_CAMERA;
  13823. _this.isIntermediate = false;
  13824. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  13825. _this.layerMask = 0x0FFFFFFF;
  13826. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  13827. // Camera rig members
  13828. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  13829. _this._rigCameras = new Array();
  13830. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  13831. // Cache
  13832. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  13833. _this._projectionMatrix = new BABYLON.Matrix();
  13834. _this._doNotComputeProjectionMatrix = false;
  13835. _this._postProcesses = new Array();
  13836. _this._transformMatrix = BABYLON.Matrix.Zero();
  13837. _this._activeMeshes = new BABYLON.SmartArray(256);
  13838. _this._globalPosition = BABYLON.Vector3.Zero();
  13839. _this._refreshFrustumPlanes = true;
  13840. _this.getScene().addCamera(_this);
  13841. if (!_this.getScene().activeCamera) {
  13842. _this.getScene().activeCamera = _this;
  13843. }
  13844. _this.position = position;
  13845. return _this;
  13846. }
  13847. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  13848. get: function () {
  13849. return Camera._PERSPECTIVE_CAMERA;
  13850. },
  13851. enumerable: true,
  13852. configurable: true
  13853. });
  13854. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  13855. get: function () {
  13856. return Camera._ORTHOGRAPHIC_CAMERA;
  13857. },
  13858. enumerable: true,
  13859. configurable: true
  13860. });
  13861. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  13862. get: function () {
  13863. return Camera._FOVMODE_VERTICAL_FIXED;
  13864. },
  13865. enumerable: true,
  13866. configurable: true
  13867. });
  13868. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  13869. get: function () {
  13870. return Camera._FOVMODE_HORIZONTAL_FIXED;
  13871. },
  13872. enumerable: true,
  13873. configurable: true
  13874. });
  13875. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  13876. get: function () {
  13877. return Camera._RIG_MODE_NONE;
  13878. },
  13879. enumerable: true,
  13880. configurable: true
  13881. });
  13882. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  13883. get: function () {
  13884. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  13885. },
  13886. enumerable: true,
  13887. configurable: true
  13888. });
  13889. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  13890. get: function () {
  13891. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  13892. },
  13893. enumerable: true,
  13894. configurable: true
  13895. });
  13896. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  13897. get: function () {
  13898. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13899. },
  13900. enumerable: true,
  13901. configurable: true
  13902. });
  13903. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  13904. get: function () {
  13905. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  13906. },
  13907. enumerable: true,
  13908. configurable: true
  13909. });
  13910. Object.defineProperty(Camera, "RIG_MODE_VR", {
  13911. get: function () {
  13912. return Camera._RIG_MODE_VR;
  13913. },
  13914. enumerable: true,
  13915. configurable: true
  13916. });
  13917. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  13918. get: function () {
  13919. return Camera._RIG_MODE_WEBVR;
  13920. },
  13921. enumerable: true,
  13922. configurable: true
  13923. });
  13924. Camera.prototype.getClassName = function () {
  13925. return "Camera";
  13926. };
  13927. /**
  13928. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13929. */
  13930. Camera.prototype.toString = function (fullDetails) {
  13931. var ret = "Name: " + this.name;
  13932. ret += ", type: " + this.getClassName();
  13933. if (this.animations) {
  13934. for (var i = 0; i < this.animations.length; i++) {
  13935. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13936. }
  13937. }
  13938. if (fullDetails) {
  13939. }
  13940. return ret;
  13941. };
  13942. Object.defineProperty(Camera.prototype, "globalPosition", {
  13943. get: function () {
  13944. return this._globalPosition;
  13945. },
  13946. enumerable: true,
  13947. configurable: true
  13948. });
  13949. Camera.prototype.getActiveMeshes = function () {
  13950. return this._activeMeshes;
  13951. };
  13952. Camera.prototype.isActiveMesh = function (mesh) {
  13953. return (this._activeMeshes.indexOf(mesh) !== -1);
  13954. };
  13955. //Cache
  13956. Camera.prototype._initCache = function () {
  13957. _super.prototype._initCache.call(this);
  13958. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13959. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13960. this._cache.mode = undefined;
  13961. this._cache.minZ = undefined;
  13962. this._cache.maxZ = undefined;
  13963. this._cache.fov = undefined;
  13964. this._cache.fovMode = undefined;
  13965. this._cache.aspectRatio = undefined;
  13966. this._cache.orthoLeft = undefined;
  13967. this._cache.orthoRight = undefined;
  13968. this._cache.orthoBottom = undefined;
  13969. this._cache.orthoTop = undefined;
  13970. this._cache.renderWidth = undefined;
  13971. this._cache.renderHeight = undefined;
  13972. };
  13973. Camera.prototype._updateCache = function (ignoreParentClass) {
  13974. if (!ignoreParentClass) {
  13975. _super.prototype._updateCache.call(this);
  13976. }
  13977. var engine = this.getEngine();
  13978. this._cache.position.copyFrom(this.position);
  13979. this._cache.upVector.copyFrom(this.upVector);
  13980. this._cache.mode = this.mode;
  13981. this._cache.minZ = this.minZ;
  13982. this._cache.maxZ = this.maxZ;
  13983. this._cache.fov = this.fov;
  13984. this._cache.fovMode = this.fovMode;
  13985. this._cache.aspectRatio = engine.getAspectRatio(this);
  13986. this._cache.orthoLeft = this.orthoLeft;
  13987. this._cache.orthoRight = this.orthoRight;
  13988. this._cache.orthoBottom = this.orthoBottom;
  13989. this._cache.orthoTop = this.orthoTop;
  13990. this._cache.renderWidth = engine.getRenderWidth();
  13991. this._cache.renderHeight = engine.getRenderHeight();
  13992. };
  13993. Camera.prototype._updateFromScene = function () {
  13994. this.updateCache();
  13995. this.update();
  13996. };
  13997. // Synchronized
  13998. Camera.prototype._isSynchronized = function () {
  13999. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  14000. };
  14001. Camera.prototype._isSynchronizedViewMatrix = function () {
  14002. if (!_super.prototype._isSynchronized.call(this))
  14003. return false;
  14004. return this._cache.position.equals(this.position)
  14005. && this._cache.upVector.equals(this.upVector)
  14006. && this.isSynchronizedWithParent();
  14007. };
  14008. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  14009. var check = this._cache.mode === this.mode
  14010. && this._cache.minZ === this.minZ
  14011. && this._cache.maxZ === this.maxZ;
  14012. if (!check) {
  14013. return false;
  14014. }
  14015. var engine = this.getEngine();
  14016. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14017. check = this._cache.fov === this.fov
  14018. && this._cache.fovMode === this.fovMode
  14019. && this._cache.aspectRatio === engine.getAspectRatio(this);
  14020. }
  14021. else {
  14022. check = this._cache.orthoLeft === this.orthoLeft
  14023. && this._cache.orthoRight === this.orthoRight
  14024. && this._cache.orthoBottom === this.orthoBottom
  14025. && this._cache.orthoTop === this.orthoTop
  14026. && this._cache.renderWidth === engine.getRenderWidth()
  14027. && this._cache.renderHeight === engine.getRenderHeight();
  14028. }
  14029. return check;
  14030. };
  14031. // Controls
  14032. Camera.prototype.attachControl = function (element, noPreventDefault) {
  14033. };
  14034. Camera.prototype.detachControl = function (element) {
  14035. };
  14036. Camera.prototype.update = function () {
  14037. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14038. this._updateRigCameras();
  14039. }
  14040. this._checkInputs();
  14041. };
  14042. Camera.prototype._checkInputs = function () {
  14043. };
  14044. Object.defineProperty(Camera.prototype, "rigCameras", {
  14045. get: function () {
  14046. return this._rigCameras;
  14047. },
  14048. enumerable: true,
  14049. configurable: true
  14050. });
  14051. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  14052. get: function () {
  14053. return this._rigPostProcess;
  14054. },
  14055. enumerable: true,
  14056. configurable: true
  14057. });
  14058. Camera.prototype._cascadePostProcessesToRigCams = function () {
  14059. // invalidate framebuffer
  14060. if (this._postProcesses.length > 0) {
  14061. this._postProcesses[0].markTextureDirty();
  14062. }
  14063. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  14064. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  14065. var cam = this._rigCameras[i];
  14066. var rigPostProcess = cam._rigPostProcess;
  14067. // for VR rig, there does not have to be a post process
  14068. if (rigPostProcess) {
  14069. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  14070. if (isPass) {
  14071. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  14072. cam.isIntermediate = this._postProcesses.length === 0;
  14073. }
  14074. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  14075. rigPostProcess.markTextureDirty();
  14076. }
  14077. else {
  14078. cam._postProcesses = this._postProcesses.slice(0);
  14079. }
  14080. }
  14081. };
  14082. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  14083. if (insertAt === void 0) { insertAt = null; }
  14084. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  14085. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  14086. return 0;
  14087. }
  14088. if (insertAt == null || insertAt < 0) {
  14089. this._postProcesses.push(postProcess);
  14090. }
  14091. else {
  14092. this._postProcesses.splice(insertAt, 0, postProcess);
  14093. }
  14094. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14095. return this._postProcesses.indexOf(postProcess);
  14096. };
  14097. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  14098. if (atIndices === void 0) { atIndices = null; }
  14099. var result = [];
  14100. var i;
  14101. var index;
  14102. if (!atIndices) {
  14103. var idx = this._postProcesses.indexOf(postProcess);
  14104. if (idx !== -1) {
  14105. this._postProcesses.splice(idx, 1);
  14106. }
  14107. }
  14108. else {
  14109. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  14110. // iterate descending, so can just splice as we go
  14111. for (i = atIndices.length - 1; i >= 0; i--) {
  14112. if (this._postProcesses[atIndices[i]] !== postProcess) {
  14113. result.push(i);
  14114. continue;
  14115. }
  14116. index = atIndices[i];
  14117. this._postProcesses.splice(index, 1);
  14118. }
  14119. }
  14120. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14121. return result;
  14122. };
  14123. Camera.prototype.getWorldMatrix = function () {
  14124. if (!this._worldMatrix) {
  14125. this._worldMatrix = BABYLON.Matrix.Identity();
  14126. }
  14127. var viewMatrix = this.getViewMatrix();
  14128. viewMatrix.invertToRef(this._worldMatrix);
  14129. return this._worldMatrix;
  14130. };
  14131. Camera.prototype._getViewMatrix = function () {
  14132. return BABYLON.Matrix.Identity();
  14133. };
  14134. Camera.prototype.getViewMatrix = function (force) {
  14135. this._computedViewMatrix = this._computeViewMatrix(force);
  14136. if (!force && this._isSynchronizedViewMatrix()) {
  14137. return this._computedViewMatrix;
  14138. }
  14139. this._refreshFrustumPlanes = true;
  14140. if (!this.parent || !this.parent.getWorldMatrix) {
  14141. this._globalPosition.copyFrom(this.position);
  14142. }
  14143. else {
  14144. if (!this._worldMatrix) {
  14145. this._worldMatrix = BABYLON.Matrix.Identity();
  14146. }
  14147. this._computedViewMatrix.invertToRef(this._worldMatrix);
  14148. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  14149. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  14150. this._computedViewMatrix.invert();
  14151. this._markSyncedWithParent();
  14152. }
  14153. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  14154. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  14155. }
  14156. this._currentRenderId = this.getScene().getRenderId();
  14157. return this._computedViewMatrix;
  14158. };
  14159. Camera.prototype._computeViewMatrix = function (force) {
  14160. if (!force && this._isSynchronizedViewMatrix()) {
  14161. return this._computedViewMatrix;
  14162. }
  14163. this._computedViewMatrix = this._getViewMatrix();
  14164. this._currentRenderId = this.getScene().getRenderId();
  14165. return this._computedViewMatrix;
  14166. };
  14167. Camera.prototype.freezeProjectionMatrix = function (projection) {
  14168. this._doNotComputeProjectionMatrix = true;
  14169. if (projection !== undefined) {
  14170. this._projectionMatrix = projection;
  14171. }
  14172. };
  14173. ;
  14174. Camera.prototype.unfreezeProjectionMatrix = function () {
  14175. this._doNotComputeProjectionMatrix = false;
  14176. };
  14177. ;
  14178. Camera.prototype.getProjectionMatrix = function (force) {
  14179. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  14180. return this._projectionMatrix;
  14181. }
  14182. this._refreshFrustumPlanes = true;
  14183. var engine = this.getEngine();
  14184. var scene = this.getScene();
  14185. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14186. if (this.minZ <= 0) {
  14187. this.minZ = 0.1;
  14188. }
  14189. if (scene.useRightHandedSystem) {
  14190. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14191. }
  14192. else {
  14193. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14194. }
  14195. return this._projectionMatrix;
  14196. }
  14197. var halfWidth = engine.getRenderWidth() / 2.0;
  14198. var halfHeight = engine.getRenderHeight() / 2.0;
  14199. if (scene.useRightHandedSystem) {
  14200. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14201. }
  14202. else {
  14203. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14204. }
  14205. return this._projectionMatrix;
  14206. };
  14207. Camera.prototype.getTranformationMatrix = function () {
  14208. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14209. return this._transformMatrix;
  14210. };
  14211. Camera.prototype.updateFrustumPlanes = function () {
  14212. if (!this._refreshFrustumPlanes) {
  14213. return;
  14214. }
  14215. this.getTranformationMatrix();
  14216. if (!this._frustumPlanes) {
  14217. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  14218. }
  14219. else {
  14220. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  14221. }
  14222. this._refreshFrustumPlanes = false;
  14223. };
  14224. Camera.prototype.isInFrustum = function (target) {
  14225. this.updateFrustumPlanes();
  14226. return target.isInFrustum(this._frustumPlanes);
  14227. };
  14228. Camera.prototype.isCompletelyInFrustum = function (target) {
  14229. this.updateFrustumPlanes();
  14230. return target.isCompletelyInFrustum(this._frustumPlanes);
  14231. };
  14232. Camera.prototype.getForwardRay = function (length, transform, origin) {
  14233. if (length === void 0) { length = 100; }
  14234. if (!transform) {
  14235. transform = this.getWorldMatrix();
  14236. }
  14237. if (!origin) {
  14238. origin = this.position;
  14239. }
  14240. var forward = new BABYLON.Vector3(0, 0, 1);
  14241. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  14242. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  14243. return new BABYLON.Ray(origin, direction, length);
  14244. };
  14245. Camera.prototype.dispose = function () {
  14246. // Animations
  14247. this.getScene().stopAnimation(this);
  14248. // Remove from scene
  14249. this.getScene().removeCamera(this);
  14250. while (this._rigCameras.length > 0) {
  14251. this._rigCameras.pop().dispose();
  14252. }
  14253. // Postprocesses
  14254. var i = this._postProcesses.length;
  14255. while (--i >= 0) {
  14256. this._postProcesses[i].dispose(this);
  14257. }
  14258. _super.prototype.dispose.call(this);
  14259. };
  14260. Object.defineProperty(Camera.prototype, "leftCamera", {
  14261. // ---- Camera rigs section ----
  14262. get: function () {
  14263. if (this._rigCameras.length < 1) {
  14264. return undefined;
  14265. }
  14266. return this._rigCameras[0];
  14267. },
  14268. enumerable: true,
  14269. configurable: true
  14270. });
  14271. Object.defineProperty(Camera.prototype, "rightCamera", {
  14272. get: function () {
  14273. if (this._rigCameras.length < 2) {
  14274. return undefined;
  14275. }
  14276. return this._rigCameras[1];
  14277. },
  14278. enumerable: true,
  14279. configurable: true
  14280. });
  14281. Camera.prototype.getLeftTarget = function () {
  14282. if (this._rigCameras.length < 1) {
  14283. return undefined;
  14284. }
  14285. return this._rigCameras[0].getTarget();
  14286. };
  14287. Camera.prototype.getRightTarget = function () {
  14288. if (this._rigCameras.length < 2) {
  14289. return undefined;
  14290. }
  14291. return this._rigCameras[1].getTarget();
  14292. };
  14293. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  14294. while (this._rigCameras.length > 0) {
  14295. this._rigCameras.pop().dispose();
  14296. }
  14297. this.cameraRigMode = mode;
  14298. this._cameraRigParams = {};
  14299. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  14300. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  14301. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  14302. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  14303. // create the rig cameras, unless none
  14304. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14305. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  14306. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  14307. }
  14308. switch (this.cameraRigMode) {
  14309. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14310. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14311. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  14312. break;
  14313. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14314. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14315. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14316. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14317. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14318. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  14319. break;
  14320. case Camera.RIG_MODE_VR:
  14321. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  14322. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  14323. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14324. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14325. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  14326. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  14327. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  14328. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  14329. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14330. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14331. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  14332. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  14333. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  14334. if (metrics.compensateDistortion) {
  14335. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  14336. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  14337. }
  14338. break;
  14339. case Camera.RIG_MODE_WEBVR:
  14340. if (rigParams.vrDisplay) {
  14341. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  14342. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  14343. //Left eye
  14344. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14345. this._rigCameras[0].setCameraRigParameter("left", true);
  14346. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  14347. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  14348. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  14349. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14350. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14351. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14352. this._rigCameras[0].parent = this;
  14353. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  14354. //Right eye
  14355. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14356. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  14357. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  14358. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  14359. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  14360. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14361. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14362. this._rigCameras[1].parent = this;
  14363. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  14364. }
  14365. break;
  14366. }
  14367. this._cascadePostProcessesToRigCams();
  14368. this.
  14369. update();
  14370. };
  14371. Camera.prototype._getVRProjectionMatrix = function () {
  14372. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  14373. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  14374. return this._projectionMatrix;
  14375. };
  14376. Camera.prototype._updateCameraRotationMatrix = function () {
  14377. //Here for WebVR
  14378. };
  14379. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  14380. //Here for WebVR
  14381. };
  14382. /**
  14383. * This function MUST be overwritten by the different WebVR cameras available.
  14384. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14385. */
  14386. Camera.prototype._getWebVRProjectionMatrix = function () {
  14387. return BABYLON.Matrix.Identity();
  14388. };
  14389. /**
  14390. * This function MUST be overwritten by the different WebVR cameras available.
  14391. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  14392. */
  14393. Camera.prototype._getWebVRViewMatrix = function () {
  14394. return BABYLON.Matrix.Identity();
  14395. };
  14396. Camera.prototype.setCameraRigParameter = function (name, value) {
  14397. if (!this._cameraRigParams) {
  14398. this._cameraRigParams = {};
  14399. }
  14400. this._cameraRigParams[name] = value;
  14401. //provisionnally:
  14402. if (name === "interaxialDistance") {
  14403. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  14404. }
  14405. };
  14406. /**
  14407. * needs to be overridden by children so sub has required properties to be copied
  14408. */
  14409. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  14410. return null;
  14411. };
  14412. /**
  14413. * May need to be overridden by children
  14414. */
  14415. Camera.prototype._updateRigCameras = function () {
  14416. for (var i = 0; i < this._rigCameras.length; i++) {
  14417. this._rigCameras[i].minZ = this.minZ;
  14418. this._rigCameras[i].maxZ = this.maxZ;
  14419. this._rigCameras[i].fov = this.fov;
  14420. }
  14421. // only update viewport when ANAGLYPH
  14422. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  14423. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  14424. }
  14425. };
  14426. Camera.prototype._setupInputs = function () {
  14427. };
  14428. Camera.prototype.serialize = function () {
  14429. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14430. // Type
  14431. serializationObject.type = this.getClassName();
  14432. // Parent
  14433. if (this.parent) {
  14434. serializationObject.parentId = this.parent.id;
  14435. }
  14436. if (this.inputs) {
  14437. this.inputs.serialize(serializationObject);
  14438. }
  14439. // Animations
  14440. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14441. serializationObject.ranges = this.serializeAnimationRanges();
  14442. return serializationObject;
  14443. };
  14444. Camera.prototype.clone = function (name) {
  14445. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  14446. };
  14447. Camera.prototype.getDirection = function (localAxis) {
  14448. var result = BABYLON.Vector3.Zero();
  14449. this.getDirectionToRef(localAxis, result);
  14450. return result;
  14451. };
  14452. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  14453. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14454. };
  14455. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  14456. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  14457. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  14458. switch (type) {
  14459. case "ArcRotateCamera":
  14460. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  14461. case "DeviceOrientationCamera":
  14462. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  14463. case "FollowCamera":
  14464. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  14465. case "ArcFollowCamera":
  14466. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  14467. case "GamepadCamera":
  14468. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14469. case "TouchCamera":
  14470. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  14471. case "VirtualJoysticksCamera":
  14472. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  14473. case "WebVRFreeCamera":
  14474. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14475. case "WebVRGamepadCamera":
  14476. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14477. case "VRDeviceOrientationFreeCamera":
  14478. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14479. case "VRDeviceOrientationGamepadCamera":
  14480. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14481. case "AnaglyphArcRotateCamera":
  14482. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14483. case "AnaglyphFreeCamera":
  14484. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14485. case "AnaglyphGamepadCamera":
  14486. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14487. case "AnaglyphUniversalCamera":
  14488. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14489. case "StereoscopicArcRotateCamera":
  14490. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14491. case "StereoscopicFreeCamera":
  14492. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14493. case "StereoscopicGamepadCamera":
  14494. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14495. case "StereoscopicUniversalCamera":
  14496. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14497. case "FreeCamera":
  14498. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14499. default:
  14500. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14501. }
  14502. };
  14503. Camera.Parse = function (parsedCamera, scene) {
  14504. var type = parsedCamera.type;
  14505. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  14506. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  14507. // Parent
  14508. if (parsedCamera.parentId) {
  14509. camera._waitingParentId = parsedCamera.parentId;
  14510. }
  14511. //If camera has an input manager, let it parse inputs settings
  14512. if (camera.inputs) {
  14513. camera.inputs.parse(parsedCamera);
  14514. camera._setupInputs();
  14515. }
  14516. // Target
  14517. if (parsedCamera.target) {
  14518. if (camera.setTarget) {
  14519. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  14520. }
  14521. }
  14522. // Apply 3d rig, when found
  14523. if (parsedCamera.cameraRigMode) {
  14524. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  14525. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  14526. }
  14527. // Animations
  14528. if (parsedCamera.animations) {
  14529. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  14530. var parsedAnimation = parsedCamera.animations[animationIndex];
  14531. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14532. }
  14533. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  14534. }
  14535. if (parsedCamera.autoAnimate) {
  14536. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  14537. }
  14538. return camera;
  14539. };
  14540. return Camera;
  14541. }(BABYLON.Node));
  14542. // Statics
  14543. Camera._PERSPECTIVE_CAMERA = 0;
  14544. Camera._ORTHOGRAPHIC_CAMERA = 1;
  14545. Camera._FOVMODE_VERTICAL_FIXED = 0;
  14546. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  14547. Camera._RIG_MODE_NONE = 0;
  14548. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  14549. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  14550. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  14551. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  14552. Camera._RIG_MODE_VR = 20;
  14553. Camera._RIG_MODE_WEBVR = 21;
  14554. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  14555. __decorate([
  14556. BABYLON.serializeAsVector3()
  14557. ], Camera.prototype, "position", void 0);
  14558. __decorate([
  14559. BABYLON.serializeAsVector3()
  14560. ], Camera.prototype, "upVector", void 0);
  14561. __decorate([
  14562. BABYLON.serialize()
  14563. ], Camera.prototype, "orthoLeft", void 0);
  14564. __decorate([
  14565. BABYLON.serialize()
  14566. ], Camera.prototype, "orthoRight", void 0);
  14567. __decorate([
  14568. BABYLON.serialize()
  14569. ], Camera.prototype, "orthoBottom", void 0);
  14570. __decorate([
  14571. BABYLON.serialize()
  14572. ], Camera.prototype, "orthoTop", void 0);
  14573. __decorate([
  14574. BABYLON.serialize()
  14575. ], Camera.prototype, "fov", void 0);
  14576. __decorate([
  14577. BABYLON.serialize()
  14578. ], Camera.prototype, "minZ", void 0);
  14579. __decorate([
  14580. BABYLON.serialize()
  14581. ], Camera.prototype, "maxZ", void 0);
  14582. __decorate([
  14583. BABYLON.serialize()
  14584. ], Camera.prototype, "inertia", void 0);
  14585. __decorate([
  14586. BABYLON.serialize()
  14587. ], Camera.prototype, "mode", void 0);
  14588. __decorate([
  14589. BABYLON.serialize()
  14590. ], Camera.prototype, "layerMask", void 0);
  14591. __decorate([
  14592. BABYLON.serialize()
  14593. ], Camera.prototype, "fovMode", void 0);
  14594. __decorate([
  14595. BABYLON.serialize()
  14596. ], Camera.prototype, "cameraRigMode", void 0);
  14597. __decorate([
  14598. BABYLON.serialize()
  14599. ], Camera.prototype, "interaxialDistance", void 0);
  14600. __decorate([
  14601. BABYLON.serialize()
  14602. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  14603. BABYLON.Camera = Camera;
  14604. })(BABYLON || (BABYLON = {}));
  14605. //# sourceMappingURL=babylon.camera.js.map
  14606. var BABYLON;
  14607. (function (BABYLON) {
  14608. var RenderingManager = (function () {
  14609. function RenderingManager(scene) {
  14610. this._renderingGroups = new Array();
  14611. this._autoClearDepthStencil = {};
  14612. this._customOpaqueSortCompareFn = {};
  14613. this._customAlphaTestSortCompareFn = {};
  14614. this._customTransparentSortCompareFn = {};
  14615. this._renderinGroupInfo = null;
  14616. this._scene = scene;
  14617. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  14618. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  14619. }
  14620. }
  14621. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  14622. if (depth === void 0) { depth = true; }
  14623. if (stencil === void 0) { stencil = true; }
  14624. if (this._depthStencilBufferAlreadyCleaned) {
  14625. return;
  14626. }
  14627. this._scene.getEngine().clear(null, false, depth, stencil);
  14628. this._depthStencilBufferAlreadyCleaned = true;
  14629. };
  14630. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  14631. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  14632. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  14633. var info = null;
  14634. if (observable) {
  14635. if (!this._renderinGroupInfo) {
  14636. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  14637. }
  14638. info = this._renderinGroupInfo;
  14639. info.scene = this._scene;
  14640. info.camera = this._scene.activeCamera;
  14641. }
  14642. // Dispatch sprites
  14643. if (renderSprites) {
  14644. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  14645. var manager = this._scene.spriteManagers[index];
  14646. this.dispatchSprites(manager);
  14647. }
  14648. }
  14649. // Render
  14650. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14651. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  14652. var renderingGroup = this._renderingGroups[index];
  14653. if (!renderingGroup && !observable)
  14654. continue;
  14655. this._currentIndex = index;
  14656. var renderingGroupMask = 0;
  14657. // Fire PRECLEAR stage
  14658. if (observable) {
  14659. renderingGroupMask = Math.pow(2, index);
  14660. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  14661. info.renderingGroupId = index;
  14662. observable.notifyObservers(info, renderingGroupMask);
  14663. }
  14664. // Clear depth/stencil if needed
  14665. if (RenderingManager.AUTOCLEAR) {
  14666. var autoClear = this._autoClearDepthStencil[index];
  14667. if (autoClear && autoClear.autoClear) {
  14668. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  14669. }
  14670. }
  14671. if (observable) {
  14672. // Fire PREOPAQUE stage
  14673. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  14674. observable.notifyObservers(info, renderingGroupMask);
  14675. // Fire PRETRANSPARENT stage
  14676. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  14677. observable.notifyObservers(info, renderingGroupMask);
  14678. }
  14679. if (renderingGroup)
  14680. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  14681. // Fire POSTTRANSPARENT stage
  14682. if (observable) {
  14683. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  14684. observable.notifyObservers(info, renderingGroupMask);
  14685. }
  14686. }
  14687. };
  14688. RenderingManager.prototype.reset = function () {
  14689. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14690. var renderingGroup = this._renderingGroups[index];
  14691. if (renderingGroup) {
  14692. renderingGroup.prepare();
  14693. }
  14694. }
  14695. };
  14696. RenderingManager.prototype.dispose = function () {
  14697. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14698. var renderingGroup = this._renderingGroups[index];
  14699. if (renderingGroup) {
  14700. renderingGroup.dispose();
  14701. }
  14702. }
  14703. this._renderingGroups.length = 0;
  14704. };
  14705. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  14706. if (!this._renderingGroups[renderingGroupId]) {
  14707. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  14708. }
  14709. };
  14710. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  14711. var renderingGroupId = spriteManager.renderingGroupId || 0;
  14712. this._prepareRenderingGroup(renderingGroupId);
  14713. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  14714. };
  14715. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  14716. var renderingGroupId = particleSystem.renderingGroupId || 0;
  14717. this._prepareRenderingGroup(renderingGroupId);
  14718. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  14719. };
  14720. RenderingManager.prototype.dispatch = function (subMesh) {
  14721. var mesh = subMesh.getMesh();
  14722. var renderingGroupId = mesh.renderingGroupId || 0;
  14723. this._prepareRenderingGroup(renderingGroupId);
  14724. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  14725. };
  14726. /**
  14727. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  14728. * This allowed control for front to back rendering or reversly depending of the special needs.
  14729. *
  14730. * @param renderingGroupId The rendering group id corresponding to its index
  14731. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  14732. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  14733. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  14734. */
  14735. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14736. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14737. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14738. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14739. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  14740. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  14741. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  14742. if (this._renderingGroups[renderingGroupId]) {
  14743. var group = this._renderingGroups[renderingGroupId];
  14744. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  14745. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  14746. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  14747. }
  14748. };
  14749. /**
  14750. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  14751. *
  14752. * @param renderingGroupId The rendering group id corresponding to its index
  14753. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  14754. * @param depth Automatically clears depth between groups if true and autoClear is true.
  14755. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  14756. */
  14757. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  14758. if (depth === void 0) { depth = true; }
  14759. if (stencil === void 0) { stencil = true; }
  14760. this._autoClearDepthStencil[renderingGroupId] = {
  14761. autoClear: autoClearDepthStencil,
  14762. depth: depth,
  14763. stencil: stencil
  14764. };
  14765. };
  14766. return RenderingManager;
  14767. }());
  14768. /**
  14769. * The max id used for rendering groups (not included)
  14770. */
  14771. RenderingManager.MAX_RENDERINGGROUPS = 4;
  14772. /**
  14773. * The min id used for rendering groups (included)
  14774. */
  14775. RenderingManager.MIN_RENDERINGGROUPS = 0;
  14776. /**
  14777. * Used to globally prevent autoclearing scenes.
  14778. */
  14779. RenderingManager.AUTOCLEAR = true;
  14780. BABYLON.RenderingManager = RenderingManager;
  14781. })(BABYLON || (BABYLON = {}));
  14782. //# sourceMappingURL=babylon.renderingManager.js.map
  14783. var BABYLON;
  14784. (function (BABYLON) {
  14785. var RenderingGroup = (function () {
  14786. /**
  14787. * Creates a new rendering group.
  14788. * @param index The rendering group index
  14789. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  14790. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  14791. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  14792. */
  14793. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14794. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14795. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14796. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14797. this.index = index;
  14798. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  14799. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  14800. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  14801. this._particleSystems = new BABYLON.SmartArray(256);
  14802. this._spriteManagers = new BABYLON.SmartArray(256);
  14803. this._edgesRenderers = new BABYLON.SmartArray(16);
  14804. this._scene = scene;
  14805. this.opaqueSortCompareFn = opaqueSortCompareFn;
  14806. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  14807. this.transparentSortCompareFn = transparentSortCompareFn;
  14808. }
  14809. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  14810. /**
  14811. * Set the opaque sort comparison function.
  14812. * If null the sub meshes will be render in the order they were created
  14813. */
  14814. set: function (value) {
  14815. this._opaqueSortCompareFn = value;
  14816. if (value) {
  14817. this._renderOpaque = this.renderOpaqueSorted;
  14818. }
  14819. else {
  14820. this._renderOpaque = RenderingGroup.renderUnsorted;
  14821. }
  14822. },
  14823. enumerable: true,
  14824. configurable: true
  14825. });
  14826. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  14827. /**
  14828. * Set the alpha test sort comparison function.
  14829. * If null the sub meshes will be render in the order they were created
  14830. */
  14831. set: function (value) {
  14832. this._alphaTestSortCompareFn = value;
  14833. if (value) {
  14834. this._renderAlphaTest = this.renderAlphaTestSorted;
  14835. }
  14836. else {
  14837. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  14838. }
  14839. },
  14840. enumerable: true,
  14841. configurable: true
  14842. });
  14843. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  14844. /**
  14845. * Set the transparent sort comparison function.
  14846. * If null the sub meshes will be render in the order they were created
  14847. */
  14848. set: function (value) {
  14849. if (value) {
  14850. this._transparentSortCompareFn = value;
  14851. }
  14852. else {
  14853. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  14854. }
  14855. this._renderTransparent = this.renderTransparentSorted;
  14856. },
  14857. enumerable: true,
  14858. configurable: true
  14859. });
  14860. /**
  14861. * Render all the sub meshes contained in the group.
  14862. * @param customRenderFunction Used to override the default render behaviour of the group.
  14863. * @returns true if rendered some submeshes.
  14864. */
  14865. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  14866. if (customRenderFunction) {
  14867. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  14868. return;
  14869. }
  14870. var engine = this._scene.getEngine();
  14871. // Opaque
  14872. if (this._opaqueSubMeshes.length !== 0) {
  14873. this._renderOpaque(this._opaqueSubMeshes);
  14874. }
  14875. // Alpha test
  14876. if (this._alphaTestSubMeshes.length !== 0) {
  14877. engine.setAlphaTesting(true);
  14878. this._renderAlphaTest(this._alphaTestSubMeshes);
  14879. engine.setAlphaTesting(false);
  14880. }
  14881. var stencilState = engine.getStencilBuffer();
  14882. engine.setStencilBuffer(false);
  14883. // Sprites
  14884. if (renderSprites) {
  14885. this._renderSprites();
  14886. }
  14887. // Particles
  14888. if (renderParticles) {
  14889. this._renderParticles(activeMeshes);
  14890. }
  14891. if (this.onBeforeTransparentRendering) {
  14892. this.onBeforeTransparentRendering();
  14893. }
  14894. // Transparent
  14895. if (this._transparentSubMeshes.length !== 0) {
  14896. this._renderTransparent(this._transparentSubMeshes);
  14897. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14898. }
  14899. engine.setStencilBuffer(stencilState);
  14900. // Edges
  14901. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  14902. this._edgesRenderers.data[edgesRendererIndex].render();
  14903. }
  14904. };
  14905. /**
  14906. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  14907. * @param subMeshes The submeshes to render
  14908. */
  14909. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  14910. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  14911. };
  14912. /**
  14913. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  14914. * @param subMeshes The submeshes to render
  14915. */
  14916. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  14917. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  14918. };
  14919. /**
  14920. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  14921. * @param subMeshes The submeshes to render
  14922. */
  14923. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  14924. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  14925. };
  14926. /**
  14927. * Renders the submeshes in a specified order.
  14928. * @param subMeshes The submeshes to sort before render
  14929. * @param sortCompareFn The comparison function use to sort
  14930. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  14931. * @param transparent Specifies to activate blending if true
  14932. */
  14933. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  14934. var subIndex = 0;
  14935. var subMesh;
  14936. for (; subIndex < subMeshes.length; subIndex++) {
  14937. subMesh = subMeshes.data[subIndex];
  14938. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  14939. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  14940. }
  14941. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  14942. sortedArray.sort(sortCompareFn);
  14943. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  14944. subMesh = sortedArray[subIndex];
  14945. subMesh.render(transparent);
  14946. }
  14947. };
  14948. /**
  14949. * Renders the submeshes in the order they were dispatched (no sort applied).
  14950. * @param subMeshes The submeshes to render
  14951. */
  14952. RenderingGroup.renderUnsorted = function (subMeshes) {
  14953. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  14954. var submesh = subMeshes.data[subIndex];
  14955. submesh.render(false);
  14956. }
  14957. };
  14958. /**
  14959. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14960. * are rendered back to front if in the same alpha index.
  14961. *
  14962. * @param a The first submesh
  14963. * @param b The second submesh
  14964. * @returns The result of the comparison
  14965. */
  14966. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  14967. // Alpha index first
  14968. if (a._alphaIndex > b._alphaIndex) {
  14969. return 1;
  14970. }
  14971. if (a._alphaIndex < b._alphaIndex) {
  14972. return -1;
  14973. }
  14974. // Then distance to camera
  14975. return RenderingGroup.backToFrontSortCompare(a, b);
  14976. };
  14977. /**
  14978. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14979. * are rendered back to front.
  14980. *
  14981. * @param a The first submesh
  14982. * @param b The second submesh
  14983. * @returns The result of the comparison
  14984. */
  14985. RenderingGroup.backToFrontSortCompare = function (a, b) {
  14986. // Then distance to camera
  14987. if (a._distanceToCamera < b._distanceToCamera) {
  14988. return 1;
  14989. }
  14990. if (a._distanceToCamera > b._distanceToCamera) {
  14991. return -1;
  14992. }
  14993. return 0;
  14994. };
  14995. /**
  14996. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14997. * are rendered front to back (prevent overdraw).
  14998. *
  14999. * @param a The first submesh
  15000. * @param b The second submesh
  15001. * @returns The result of the comparison
  15002. */
  15003. RenderingGroup.frontToBackSortCompare = function (a, b) {
  15004. // Then distance to camera
  15005. if (a._distanceToCamera < b._distanceToCamera) {
  15006. return -1;
  15007. }
  15008. if (a._distanceToCamera > b._distanceToCamera) {
  15009. return 1;
  15010. }
  15011. return 0;
  15012. };
  15013. /**
  15014. * Resets the different lists of submeshes to prepare a new frame.
  15015. */
  15016. RenderingGroup.prototype.prepare = function () {
  15017. this._opaqueSubMeshes.reset();
  15018. this._transparentSubMeshes.reset();
  15019. this._alphaTestSubMeshes.reset();
  15020. this._particleSystems.reset();
  15021. this._spriteManagers.reset();
  15022. this._edgesRenderers.reset();
  15023. };
  15024. RenderingGroup.prototype.dispose = function () {
  15025. this._opaqueSubMeshes.dispose();
  15026. this._transparentSubMeshes.dispose();
  15027. this._alphaTestSubMeshes.dispose();
  15028. this._particleSystems.dispose();
  15029. this._spriteManagers.dispose();
  15030. this._edgesRenderers.dispose();
  15031. };
  15032. /**
  15033. * Inserts the submesh in its correct queue depending on its material.
  15034. * @param subMesh The submesh to dispatch
  15035. */
  15036. RenderingGroup.prototype.dispatch = function (subMesh) {
  15037. var material = subMesh.getMaterial();
  15038. var mesh = subMesh.getMesh();
  15039. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  15040. this._transparentSubMeshes.push(subMesh);
  15041. }
  15042. else if (material.needAlphaTesting()) {
  15043. this._alphaTestSubMeshes.push(subMesh);
  15044. }
  15045. else {
  15046. this._opaqueSubMeshes.push(subMesh); // Opaque
  15047. }
  15048. if (mesh._edgesRenderer) {
  15049. this._edgesRenderers.push(mesh._edgesRenderer);
  15050. }
  15051. };
  15052. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  15053. this._spriteManagers.push(spriteManager);
  15054. };
  15055. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  15056. this._particleSystems.push(particleSystem);
  15057. };
  15058. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  15059. if (this._particleSystems.length === 0) {
  15060. return;
  15061. }
  15062. // Particles
  15063. var activeCamera = this._scene.activeCamera;
  15064. this._scene._particlesDuration.beginMonitoring();
  15065. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15066. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  15067. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  15068. continue;
  15069. }
  15070. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  15071. this._scene._activeParticles.addCount(particleSystem.render(), false);
  15072. }
  15073. }
  15074. this._scene._particlesDuration.endMonitoring(false);
  15075. };
  15076. RenderingGroup.prototype._renderSprites = function () {
  15077. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  15078. return;
  15079. }
  15080. // Sprites
  15081. var activeCamera = this._scene.activeCamera;
  15082. this._scene._spritesDuration.beginMonitoring();
  15083. for (var id = 0; id < this._spriteManagers.length; id++) {
  15084. var spriteManager = this._spriteManagers.data[id];
  15085. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  15086. spriteManager.render();
  15087. }
  15088. }
  15089. this._scene._spritesDuration.endMonitoring(false);
  15090. };
  15091. return RenderingGroup;
  15092. }());
  15093. BABYLON.RenderingGroup = RenderingGroup;
  15094. })(BABYLON || (BABYLON = {}));
  15095. //# sourceMappingURL=babylon.renderingGroup.js.map
  15096. var BABYLON;
  15097. (function (BABYLON) {
  15098. var ClickInfo = (function () {
  15099. function ClickInfo() {
  15100. this._singleClick = false;
  15101. this._doubleClick = false;
  15102. this._hasSwiped = false;
  15103. this._ignore = false;
  15104. }
  15105. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  15106. get: function () {
  15107. return this._singleClick;
  15108. },
  15109. set: function (b) {
  15110. this._singleClick = b;
  15111. },
  15112. enumerable: true,
  15113. configurable: true
  15114. });
  15115. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  15116. get: function () {
  15117. return this._doubleClick;
  15118. },
  15119. set: function (b) {
  15120. this._doubleClick = b;
  15121. },
  15122. enumerable: true,
  15123. configurable: true
  15124. });
  15125. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  15126. get: function () {
  15127. return this._hasSwiped;
  15128. },
  15129. set: function (b) {
  15130. this._hasSwiped = b;
  15131. },
  15132. enumerable: true,
  15133. configurable: true
  15134. });
  15135. Object.defineProperty(ClickInfo.prototype, "ignore", {
  15136. get: function () {
  15137. return this._ignore;
  15138. },
  15139. set: function (b) {
  15140. this._ignore = b;
  15141. },
  15142. enumerable: true,
  15143. configurable: true
  15144. });
  15145. return ClickInfo;
  15146. }());
  15147. var PointerEventTypes = (function () {
  15148. function PointerEventTypes() {
  15149. }
  15150. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  15151. get: function () {
  15152. return PointerEventTypes._POINTERDOWN;
  15153. },
  15154. enumerable: true,
  15155. configurable: true
  15156. });
  15157. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  15158. get: function () {
  15159. return PointerEventTypes._POINTERUP;
  15160. },
  15161. enumerable: true,
  15162. configurable: true
  15163. });
  15164. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  15165. get: function () {
  15166. return PointerEventTypes._POINTERMOVE;
  15167. },
  15168. enumerable: true,
  15169. configurable: true
  15170. });
  15171. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  15172. get: function () {
  15173. return PointerEventTypes._POINTERWHEEL;
  15174. },
  15175. enumerable: true,
  15176. configurable: true
  15177. });
  15178. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  15179. get: function () {
  15180. return PointerEventTypes._POINTERPICK;
  15181. },
  15182. enumerable: true,
  15183. configurable: true
  15184. });
  15185. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  15186. get: function () {
  15187. return PointerEventTypes._POINTERTAP;
  15188. },
  15189. enumerable: true,
  15190. configurable: true
  15191. });
  15192. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  15193. get: function () {
  15194. return PointerEventTypes._POINTERDOUBLETAP;
  15195. },
  15196. enumerable: true,
  15197. configurable: true
  15198. });
  15199. return PointerEventTypes;
  15200. }());
  15201. PointerEventTypes._POINTERDOWN = 0x01;
  15202. PointerEventTypes._POINTERUP = 0x02;
  15203. PointerEventTypes._POINTERMOVE = 0x04;
  15204. PointerEventTypes._POINTERWHEEL = 0x08;
  15205. PointerEventTypes._POINTERPICK = 0x10;
  15206. PointerEventTypes._POINTERTAP = 0x20;
  15207. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  15208. BABYLON.PointerEventTypes = PointerEventTypes;
  15209. var PointerInfoBase = (function () {
  15210. function PointerInfoBase(type, event) {
  15211. this.type = type;
  15212. this.event = event;
  15213. }
  15214. return PointerInfoBase;
  15215. }());
  15216. BABYLON.PointerInfoBase = PointerInfoBase;
  15217. /**
  15218. * This class is used to store pointer related info for the onPrePointerObservable event.
  15219. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  15220. */
  15221. var PointerInfoPre = (function (_super) {
  15222. __extends(PointerInfoPre, _super);
  15223. function PointerInfoPre(type, event, localX, localY) {
  15224. var _this = _super.call(this, type, event) || this;
  15225. _this.skipOnPointerObservable = false;
  15226. _this.localPosition = new BABYLON.Vector2(localX, localY);
  15227. return _this;
  15228. }
  15229. return PointerInfoPre;
  15230. }(PointerInfoBase));
  15231. BABYLON.PointerInfoPre = PointerInfoPre;
  15232. /**
  15233. * This type contains all the data related to a pointer event in Babylon.js.
  15234. * 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.
  15235. */
  15236. var PointerInfo = (function (_super) {
  15237. __extends(PointerInfo, _super);
  15238. function PointerInfo(type, event, pickInfo) {
  15239. var _this = _super.call(this, type, event) || this;
  15240. _this.pickInfo = pickInfo;
  15241. return _this;
  15242. }
  15243. return PointerInfo;
  15244. }(PointerInfoBase));
  15245. BABYLON.PointerInfo = PointerInfo;
  15246. /**
  15247. * This class is used by the onRenderingGroupObservable
  15248. */
  15249. var RenderingGroupInfo = (function () {
  15250. function RenderingGroupInfo() {
  15251. }
  15252. return RenderingGroupInfo;
  15253. }());
  15254. /**
  15255. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  15256. * This stage will be fired no matter what
  15257. */
  15258. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  15259. /**
  15260. * Called before opaque object are rendered.
  15261. * This stage will be fired only if there's 3D Opaque content to render
  15262. */
  15263. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  15264. /**
  15265. * Called after the opaque objects are rendered and before the transparent ones
  15266. * This stage will be fired only if there's 3D transparent content to render
  15267. */
  15268. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  15269. /**
  15270. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  15271. * This stage will be fired no matter what
  15272. */
  15273. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  15274. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  15275. /**
  15276. * Represents a scene to be rendered by the engine.
  15277. * @see http://doc.babylonjs.com/page.php?p=21911
  15278. */
  15279. var Scene = (function () {
  15280. /**
  15281. * @constructor
  15282. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  15283. */
  15284. function Scene(engine) {
  15285. // Members
  15286. this.autoClear = true;
  15287. this.autoClearDepthAndStencil = true;
  15288. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  15289. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  15290. this.forceWireframe = false;
  15291. this._forcePointsCloud = false;
  15292. this.forceShowBoundingBoxes = false;
  15293. this.animationsEnabled = true;
  15294. this.constantlyUpdateMeshUnderPointer = false;
  15295. this.hoverCursor = "pointer";
  15296. // Metadata
  15297. this.metadata = null;
  15298. // Events
  15299. /**
  15300. * An event triggered when the scene is disposed.
  15301. * @type {BABYLON.Observable}
  15302. */
  15303. this.onDisposeObservable = new BABYLON.Observable();
  15304. /**
  15305. * An event triggered before rendering the scene
  15306. * @type {BABYLON.Observable}
  15307. */
  15308. this.onBeforeRenderObservable = new BABYLON.Observable();
  15309. /**
  15310. * An event triggered after rendering the scene
  15311. * @type {BABYLON.Observable}
  15312. */
  15313. this.onAfterRenderObservable = new BABYLON.Observable();
  15314. /**
  15315. * An event triggered when the scene is ready
  15316. * @type {BABYLON.Observable}
  15317. */
  15318. this.onReadyObservable = new BABYLON.Observable();
  15319. /**
  15320. * An event triggered before rendering a camera
  15321. * @type {BABYLON.Observable}
  15322. */
  15323. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  15324. /**
  15325. * An event triggered after rendering a camera
  15326. * @type {BABYLON.Observable}
  15327. */
  15328. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  15329. /**
  15330. * An event triggered when a camera is created
  15331. * @type {BABYLON.Observable}
  15332. */
  15333. this.onNewCameraAddedObservable = new BABYLON.Observable();
  15334. /**
  15335. * An event triggered when a camera is removed
  15336. * @type {BABYLON.Observable}
  15337. */
  15338. this.onCameraRemovedObservable = new BABYLON.Observable();
  15339. /**
  15340. * An event triggered when a light is created
  15341. * @type {BABYLON.Observable}
  15342. */
  15343. this.onNewLightAddedObservable = new BABYLON.Observable();
  15344. /**
  15345. * An event triggered when a light is removed
  15346. * @type {BABYLON.Observable}
  15347. */
  15348. this.onLightRemovedObservable = new BABYLON.Observable();
  15349. /**
  15350. * An event triggered when a geometry is created
  15351. * @type {BABYLON.Observable}
  15352. */
  15353. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  15354. /**
  15355. * An event triggered when a geometry is removed
  15356. * @type {BABYLON.Observable}
  15357. */
  15358. this.onGeometryRemovedObservable = new BABYLON.Observable();
  15359. /**
  15360. * An event triggered when a mesh is created
  15361. * @type {BABYLON.Observable}
  15362. */
  15363. this.onNewMeshAddedObservable = new BABYLON.Observable();
  15364. /**
  15365. * An event triggered when a mesh is removed
  15366. * @type {BABYLON.Observable}
  15367. */
  15368. this.onMeshRemovedObservable = new BABYLON.Observable();
  15369. /**
  15370. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  15371. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  15372. * 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)
  15373. */
  15374. this.onRenderingGroupObservable = new BABYLON.Observable();
  15375. // Animations
  15376. this.animations = [];
  15377. /**
  15378. * 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).
  15379. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  15380. */
  15381. this.onPrePointerObservable = new BABYLON.Observable();
  15382. /**
  15383. * Observable event triggered each time an input event is received from the rendering canvas
  15384. */
  15385. this.onPointerObservable = new BABYLON.Observable();
  15386. this._meshPickProceed = false;
  15387. this._previousHasSwiped = false;
  15388. this._currentPickResult = null;
  15389. this._previousPickResult = null;
  15390. this._isButtonPressed = false;
  15391. this._doubleClickOccured = false;
  15392. 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
  15393. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  15394. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  15395. this._startingPointerTime = 0;
  15396. this._previousStartingPointerTime = 0;
  15397. // Coordinate system
  15398. /**
  15399. * use right-handed coordinate system on this scene.
  15400. * @type {boolean}
  15401. */
  15402. this._useRightHandedSystem = false;
  15403. // Fog
  15404. /**
  15405. * is fog enabled on this scene.
  15406. * @type {boolean}
  15407. */
  15408. this._fogEnabled = true;
  15409. this._fogMode = Scene.FOGMODE_NONE;
  15410. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15411. this.fogDensity = 0.1;
  15412. this.fogStart = 0;
  15413. this.fogEnd = 1000.0;
  15414. // Lights
  15415. /**
  15416. * is shadow enabled on this scene.
  15417. * @type {boolean}
  15418. */
  15419. this._shadowsEnabled = true;
  15420. /**
  15421. * is light enabled on this scene.
  15422. * @type {boolean}
  15423. */
  15424. this._lightsEnabled = true;
  15425. /**
  15426. * All of the lights added to this scene.
  15427. * @see BABYLON.Light
  15428. * @type {BABYLON.Light[]}
  15429. */
  15430. this.lights = new Array();
  15431. // Cameras
  15432. /**
  15433. * All of the cameras added to this scene.
  15434. * @see BABYLON.Camera
  15435. * @type {BABYLON.Camera[]}
  15436. */
  15437. this.cameras = new Array();
  15438. this.activeCameras = new Array();
  15439. // Meshes
  15440. /**
  15441. * All of the (abstract) meshes added to this scene.
  15442. * @see BABYLON.AbstractMesh
  15443. * @type {BABYLON.AbstractMesh[]}
  15444. */
  15445. this.meshes = new Array();
  15446. // Geometries
  15447. this._geometries = new Array();
  15448. this.materials = new Array();
  15449. this.multiMaterials = new Array();
  15450. // Textures
  15451. this._texturesEnabled = true;
  15452. this.textures = new Array();
  15453. // Particles
  15454. this.particlesEnabled = true;
  15455. this.particleSystems = new Array();
  15456. // Sprites
  15457. this.spritesEnabled = true;
  15458. this.spriteManagers = new Array();
  15459. // Layers
  15460. this.layers = new Array();
  15461. this.highlightLayers = new Array();
  15462. // Skeletons
  15463. this._skeletonsEnabled = true;
  15464. this.skeletons = new Array();
  15465. // Morph targets
  15466. this.morphTargetManagers = new Array();
  15467. // Lens flares
  15468. this.lensFlaresEnabled = true;
  15469. this.lensFlareSystems = new Array();
  15470. // Collisions
  15471. this.collisionsEnabled = true;
  15472. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  15473. // Postprocesses
  15474. this.postProcessesEnabled = true;
  15475. // Customs render targets
  15476. this.renderTargetsEnabled = true;
  15477. this.dumpNextRenderTargets = false;
  15478. this.customRenderTargets = new Array();
  15479. // Imported meshes
  15480. this.importedMeshesFiles = new Array();
  15481. // Probes
  15482. this.probesEnabled = true;
  15483. this.reflectionProbes = new Array();
  15484. this._actionManagers = new Array();
  15485. this._meshesForIntersections = new BABYLON.SmartArray(256);
  15486. // Procedural textures
  15487. this.proceduralTexturesEnabled = true;
  15488. this._proceduralTextures = new Array();
  15489. this.soundTracks = new Array();
  15490. this._audioEnabled = true;
  15491. this._headphone = false;
  15492. // Performance counters
  15493. this._totalMeshesCounter = new BABYLON.PerfCounter();
  15494. this._totalLightsCounter = new BABYLON.PerfCounter();
  15495. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  15496. this._totalTexturesCounter = new BABYLON.PerfCounter();
  15497. this._totalVertices = new BABYLON.PerfCounter();
  15498. this._activeIndices = new BABYLON.PerfCounter();
  15499. this._activeParticles = new BABYLON.PerfCounter();
  15500. this._lastFrameDuration = new BABYLON.PerfCounter();
  15501. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  15502. this._renderTargetsDuration = new BABYLON.PerfCounter();
  15503. this._particlesDuration = new BABYLON.PerfCounter();
  15504. this._renderDuration = new BABYLON.PerfCounter();
  15505. this._spritesDuration = new BABYLON.PerfCounter();
  15506. this._activeBones = new BABYLON.PerfCounter();
  15507. this._animationTime = 0;
  15508. this.animationTimeScale = 1;
  15509. this._renderId = 0;
  15510. this._executeWhenReadyTimeoutId = -1;
  15511. this._intermediateRendering = false;
  15512. this._viewUpdateFlag = -1;
  15513. this._projectionUpdateFlag = -1;
  15514. this._toBeDisposed = new BABYLON.SmartArray(256);
  15515. this._pendingData = []; //ANY
  15516. this._activeMeshes = new BABYLON.SmartArray(256);
  15517. this._processedMaterials = new BABYLON.SmartArray(256);
  15518. this._renderTargets = new BABYLON.SmartArray(256);
  15519. this._activeParticleSystems = new BABYLON.SmartArray(256);
  15520. this._activeSkeletons = new BABYLON.SmartArray(32);
  15521. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  15522. this._activeAnimatables = new Array();
  15523. this._transformMatrix = BABYLON.Matrix.Zero();
  15524. this.requireLightSorting = false;
  15525. this._uniqueIdCounter = 0;
  15526. this.offscreenRenderTarget = null;
  15527. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  15528. this._engine.scenes.push(this);
  15529. this._uid = null;
  15530. this._renderingManager = new BABYLON.RenderingManager(this);
  15531. this.postProcessManager = new BABYLON.PostProcessManager(this);
  15532. if (BABYLON.OutlineRenderer) {
  15533. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  15534. }
  15535. this.attachControl();
  15536. if (BABYLON.SoundTrack) {
  15537. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  15538. }
  15539. //simplification queue
  15540. if (BABYLON.SimplificationQueue) {
  15541. this.simplificationQueue = new BABYLON.SimplificationQueue();
  15542. }
  15543. //collision coordinator initialization. For now legacy per default.
  15544. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  15545. // Uniform Buffer
  15546. this._createUbo();
  15547. }
  15548. Object.defineProperty(Scene, "FOGMODE_NONE", {
  15549. get: function () {
  15550. return Scene._FOGMODE_NONE;
  15551. },
  15552. enumerable: true,
  15553. configurable: true
  15554. });
  15555. Object.defineProperty(Scene, "FOGMODE_EXP", {
  15556. get: function () {
  15557. return Scene._FOGMODE_EXP;
  15558. },
  15559. enumerable: true,
  15560. configurable: true
  15561. });
  15562. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  15563. get: function () {
  15564. return Scene._FOGMODE_EXP2;
  15565. },
  15566. enumerable: true,
  15567. configurable: true
  15568. });
  15569. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  15570. get: function () {
  15571. return Scene._FOGMODE_LINEAR;
  15572. },
  15573. enumerable: true,
  15574. configurable: true
  15575. });
  15576. Object.defineProperty(Scene.prototype, "environmentTexture", {
  15577. /**
  15578. * Texture used in all pbr material as the reflection texture.
  15579. * As in the majority of the scene they are the same (exception for multi room and so on),
  15580. * this is easier to reference from here than from all the materials.
  15581. */
  15582. get: function () {
  15583. return this._environmentTexture;
  15584. },
  15585. /**
  15586. * Texture used in all pbr material as the reflection texture.
  15587. * As in the majority of the scene they are the same (exception for multi room and so on),
  15588. * this is easier to set here than in all the materials.
  15589. */
  15590. set: function (value) {
  15591. this._environmentTexture = value;
  15592. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  15593. },
  15594. enumerable: true,
  15595. configurable: true
  15596. });
  15597. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  15598. get: function () {
  15599. return this._forcePointsCloud;
  15600. },
  15601. set: function (value) {
  15602. if (this._forcePointsCloud === value) {
  15603. return;
  15604. }
  15605. this._forcePointsCloud = value;
  15606. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15607. },
  15608. enumerable: true,
  15609. configurable: true
  15610. });
  15611. Object.defineProperty(Scene.prototype, "onDispose", {
  15612. set: function (callback) {
  15613. if (this._onDisposeObserver) {
  15614. this.onDisposeObservable.remove(this._onDisposeObserver);
  15615. }
  15616. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15617. },
  15618. enumerable: true,
  15619. configurable: true
  15620. });
  15621. Object.defineProperty(Scene.prototype, "beforeRender", {
  15622. set: function (callback) {
  15623. if (this._onBeforeRenderObserver) {
  15624. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  15625. }
  15626. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  15627. },
  15628. enumerable: true,
  15629. configurable: true
  15630. });
  15631. Object.defineProperty(Scene.prototype, "afterRender", {
  15632. set: function (callback) {
  15633. if (this._onAfterRenderObserver) {
  15634. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  15635. }
  15636. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  15637. },
  15638. enumerable: true,
  15639. configurable: true
  15640. });
  15641. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  15642. set: function (callback) {
  15643. if (this._onBeforeCameraRenderObserver) {
  15644. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  15645. }
  15646. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  15647. },
  15648. enumerable: true,
  15649. configurable: true
  15650. });
  15651. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  15652. set: function (callback) {
  15653. if (this._onAfterCameraRenderObserver) {
  15654. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  15655. }
  15656. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  15657. },
  15658. enumerable: true,
  15659. configurable: true
  15660. });
  15661. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  15662. get: function () {
  15663. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  15664. },
  15665. enumerable: true,
  15666. configurable: true
  15667. });
  15668. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  15669. get: function () {
  15670. return this._useRightHandedSystem;
  15671. },
  15672. set: function (value) {
  15673. if (this._useRightHandedSystem === value) {
  15674. return;
  15675. }
  15676. this._useRightHandedSystem = value;
  15677. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15678. },
  15679. enumerable: true,
  15680. configurable: true
  15681. });
  15682. Object.defineProperty(Scene.prototype, "fogEnabled", {
  15683. get: function () {
  15684. return this._fogEnabled;
  15685. },
  15686. set: function (value) {
  15687. if (this._fogEnabled === value) {
  15688. return;
  15689. }
  15690. this._fogEnabled = value;
  15691. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15692. },
  15693. enumerable: true,
  15694. configurable: true
  15695. });
  15696. Object.defineProperty(Scene.prototype, "fogMode", {
  15697. get: function () {
  15698. return this._fogMode;
  15699. },
  15700. set: function (value) {
  15701. if (this._fogMode === value) {
  15702. return;
  15703. }
  15704. this._fogMode = value;
  15705. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  15706. },
  15707. enumerable: true,
  15708. configurable: true
  15709. });
  15710. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  15711. get: function () {
  15712. return this._shadowsEnabled;
  15713. },
  15714. set: function (value) {
  15715. if (this._shadowsEnabled === value) {
  15716. return;
  15717. }
  15718. this._shadowsEnabled = value;
  15719. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  15720. },
  15721. enumerable: true,
  15722. configurable: true
  15723. });
  15724. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  15725. get: function () {
  15726. return this._lightsEnabled;
  15727. },
  15728. set: function (value) {
  15729. if (this._lightsEnabled === value) {
  15730. return;
  15731. }
  15732. this._lightsEnabled = value;
  15733. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  15734. },
  15735. enumerable: true,
  15736. configurable: true
  15737. });
  15738. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  15739. get: function () {
  15740. if (!this._defaultMaterial) {
  15741. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  15742. }
  15743. return this._defaultMaterial;
  15744. },
  15745. set: function (value) {
  15746. this._defaultMaterial = value;
  15747. },
  15748. enumerable: true,
  15749. configurable: true
  15750. });
  15751. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  15752. get: function () {
  15753. return this._texturesEnabled;
  15754. },
  15755. set: function (value) {
  15756. if (this._texturesEnabled === value) {
  15757. return;
  15758. }
  15759. this._texturesEnabled = value;
  15760. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  15761. },
  15762. enumerable: true,
  15763. configurable: true
  15764. });
  15765. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  15766. get: function () {
  15767. return this._skeletonsEnabled;
  15768. },
  15769. set: function (value) {
  15770. if (this._skeletonsEnabled === value) {
  15771. return;
  15772. }
  15773. this._skeletonsEnabled = value;
  15774. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  15775. },
  15776. enumerable: true,
  15777. configurable: true
  15778. });
  15779. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  15780. get: function () {
  15781. if (!this._postProcessRenderPipelineManager) {
  15782. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  15783. }
  15784. return this._postProcessRenderPipelineManager;
  15785. },
  15786. enumerable: true,
  15787. configurable: true
  15788. });
  15789. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  15790. get: function () {
  15791. return this._frustumPlanes;
  15792. },
  15793. enumerable: true,
  15794. configurable: true
  15795. });
  15796. Object.defineProperty(Scene.prototype, "debugLayer", {
  15797. // Properties
  15798. get: function () {
  15799. if (!this._debugLayer) {
  15800. this._debugLayer = new BABYLON.DebugLayer(this);
  15801. }
  15802. return this._debugLayer;
  15803. },
  15804. enumerable: true,
  15805. configurable: true
  15806. });
  15807. Object.defineProperty(Scene.prototype, "workerCollisions", {
  15808. get: function () {
  15809. return this._workerCollisions;
  15810. },
  15811. set: function (enabled) {
  15812. if (!BABYLON.CollisionCoordinatorLegacy) {
  15813. return;
  15814. }
  15815. enabled = (enabled && !!Worker);
  15816. this._workerCollisions = enabled;
  15817. if (this.collisionCoordinator) {
  15818. this.collisionCoordinator.destroy();
  15819. }
  15820. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  15821. this.collisionCoordinator.init(this);
  15822. },
  15823. enumerable: true,
  15824. configurable: true
  15825. });
  15826. Object.defineProperty(Scene.prototype, "selectionOctree", {
  15827. get: function () {
  15828. return this._selectionOctree;
  15829. },
  15830. enumerable: true,
  15831. configurable: true
  15832. });
  15833. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  15834. /**
  15835. * The mesh that is currently under the pointer.
  15836. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  15837. */
  15838. get: function () {
  15839. return this._pointerOverMesh;
  15840. },
  15841. enumerable: true,
  15842. configurable: true
  15843. });
  15844. Object.defineProperty(Scene.prototype, "pointerX", {
  15845. /**
  15846. * Current on-screen X position of the pointer
  15847. * @return {number} X position of the pointer
  15848. */
  15849. get: function () {
  15850. return this._pointerX;
  15851. },
  15852. enumerable: true,
  15853. configurable: true
  15854. });
  15855. Object.defineProperty(Scene.prototype, "pointerY", {
  15856. /**
  15857. * Current on-screen Y position of the pointer
  15858. * @return {number} Y position of the pointer
  15859. */
  15860. get: function () {
  15861. return this._pointerY;
  15862. },
  15863. enumerable: true,
  15864. configurable: true
  15865. });
  15866. Scene.prototype.getCachedMaterial = function () {
  15867. return this._cachedMaterial;
  15868. };
  15869. Scene.prototype.getCachedEffect = function () {
  15870. return this._cachedEffect;
  15871. };
  15872. Scene.prototype.getCachedVisibility = function () {
  15873. return this._cachedVisibility;
  15874. };
  15875. Scene.prototype.isCachedMaterialValid = function (material, effect, visibility) {
  15876. if (visibility === void 0) { visibility = 0; }
  15877. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  15878. };
  15879. Scene.prototype.getBoundingBoxRenderer = function () {
  15880. if (!this._boundingBoxRenderer) {
  15881. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  15882. }
  15883. return this._boundingBoxRenderer;
  15884. };
  15885. Scene.prototype.getOutlineRenderer = function () {
  15886. return this._outlineRenderer;
  15887. };
  15888. Scene.prototype.getEngine = function () {
  15889. return this._engine;
  15890. };
  15891. Scene.prototype.getTotalVertices = function () {
  15892. return this._totalVertices.current;
  15893. };
  15894. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  15895. get: function () {
  15896. return this._totalVertices;
  15897. },
  15898. enumerable: true,
  15899. configurable: true
  15900. });
  15901. Scene.prototype.getActiveIndices = function () {
  15902. return this._activeIndices.current;
  15903. };
  15904. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  15905. get: function () {
  15906. return this._activeIndices;
  15907. },
  15908. enumerable: true,
  15909. configurable: true
  15910. });
  15911. Scene.prototype.getActiveParticles = function () {
  15912. return this._activeParticles.current;
  15913. };
  15914. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  15915. get: function () {
  15916. return this._activeParticles;
  15917. },
  15918. enumerable: true,
  15919. configurable: true
  15920. });
  15921. Scene.prototype.getActiveBones = function () {
  15922. return this._activeBones.current;
  15923. };
  15924. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  15925. get: function () {
  15926. return this._activeBones;
  15927. },
  15928. enumerable: true,
  15929. configurable: true
  15930. });
  15931. // Stats
  15932. Scene.prototype.getLastFrameDuration = function () {
  15933. return this._lastFrameDuration.current;
  15934. };
  15935. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  15936. get: function () {
  15937. return this._lastFrameDuration;
  15938. },
  15939. enumerable: true,
  15940. configurable: true
  15941. });
  15942. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  15943. return this._evaluateActiveMeshesDuration.current;
  15944. };
  15945. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  15946. get: function () {
  15947. return this._evaluateActiveMeshesDuration;
  15948. },
  15949. enumerable: true,
  15950. configurable: true
  15951. });
  15952. Scene.prototype.getActiveMeshes = function () {
  15953. return this._activeMeshes;
  15954. };
  15955. Scene.prototype.getRenderTargetsDuration = function () {
  15956. return this._renderTargetsDuration.current;
  15957. };
  15958. Scene.prototype.getRenderDuration = function () {
  15959. return this._renderDuration.current;
  15960. };
  15961. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  15962. get: function () {
  15963. return this._renderDuration;
  15964. },
  15965. enumerable: true,
  15966. configurable: true
  15967. });
  15968. Scene.prototype.getParticlesDuration = function () {
  15969. return this._particlesDuration.current;
  15970. };
  15971. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  15972. get: function () {
  15973. return this._particlesDuration;
  15974. },
  15975. enumerable: true,
  15976. configurable: true
  15977. });
  15978. Scene.prototype.getSpritesDuration = function () {
  15979. return this._spritesDuration.current;
  15980. };
  15981. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  15982. get: function () {
  15983. return this._spritesDuration;
  15984. },
  15985. enumerable: true,
  15986. configurable: true
  15987. });
  15988. Scene.prototype.getAnimationRatio = function () {
  15989. return this._animationRatio;
  15990. };
  15991. Scene.prototype.getRenderId = function () {
  15992. return this._renderId;
  15993. };
  15994. Scene.prototype.incrementRenderId = function () {
  15995. this._renderId++;
  15996. };
  15997. Scene.prototype._updatePointerPosition = function (evt) {
  15998. var canvasRect = this._engine.getRenderingCanvasClientRect();
  15999. this._pointerX = evt.clientX - canvasRect.left;
  16000. this._pointerY = evt.clientY - canvasRect.top;
  16001. this._unTranslatedPointerX = this._pointerX;
  16002. this._unTranslatedPointerY = this._pointerY;
  16003. if (this.cameraToUseForPointers) {
  16004. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  16005. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  16006. }
  16007. };
  16008. Scene.prototype._createUbo = function () {
  16009. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  16010. this._sceneUbo.addUniform("viewProjection", 16);
  16011. this._sceneUbo.addUniform("view", 16);
  16012. };
  16013. // Pointers handling
  16014. /**
  16015. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  16016. * @param attachUp defines if you want to attach events to pointerup
  16017. * @param attachDown defines if you want to attach events to pointerdown
  16018. * @param attachMove defines if you want to attach events to pointermove
  16019. */
  16020. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  16021. var _this = this;
  16022. if (attachUp === void 0) { attachUp = true; }
  16023. if (attachDown === void 0) { attachDown = true; }
  16024. if (attachMove === void 0) { attachMove = true; }
  16025. this._initActionManager = function (act, clickInfo) {
  16026. if (!_this._meshPickProceed) {
  16027. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16028. _this._currentPickResult = pickResult;
  16029. if (pickResult) {
  16030. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  16031. }
  16032. _this._meshPickProceed = true;
  16033. }
  16034. return act;
  16035. };
  16036. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  16037. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  16038. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  16039. btn !== _this._previousButtonPressed) {
  16040. _this._doubleClickOccured = false;
  16041. clickInfo.singleClick = true;
  16042. clickInfo.ignore = false;
  16043. cb(clickInfo, _this._currentPickResult);
  16044. }
  16045. };
  16046. this._initClickEvent = function (obs1, obs2, evt, cb) {
  16047. var clickInfo = new ClickInfo();
  16048. _this._currentPickResult = null;
  16049. var act;
  16050. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  16051. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  16052. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16053. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  16054. act = _this._initActionManager(act, clickInfo);
  16055. if (act)
  16056. checkPicking = act.hasPickTriggers;
  16057. }
  16058. if (checkPicking) {
  16059. var btn = evt.button;
  16060. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  16061. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  16062. if (!clickInfo.hasSwiped) {
  16063. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  16064. if (!checkSingleClickImmediately) {
  16065. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  16066. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16067. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16068. act = _this._initActionManager(act, clickInfo);
  16069. if (act)
  16070. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16071. }
  16072. }
  16073. if (checkSingleClickImmediately) {
  16074. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  16075. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  16076. btn !== _this._previousButtonPressed) {
  16077. clickInfo.singleClick = true;
  16078. cb(clickInfo, _this._currentPickResult);
  16079. }
  16080. }
  16081. else {
  16082. // wait that no double click has been raised during the double click delay
  16083. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16084. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  16085. }
  16086. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  16087. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  16088. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16089. act = _this._initActionManager(act, clickInfo);
  16090. if (act)
  16091. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  16092. }
  16093. if (checkDoubleClick) {
  16094. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  16095. if (btn === _this._previousButtonPressed &&
  16096. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  16097. !_this._doubleClickOccured) {
  16098. // pointer has not moved for 2 clicks, it's a double click
  16099. if (!clickInfo.hasSwiped &&
  16100. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  16101. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  16102. _this._previousStartingPointerTime = 0;
  16103. _this._doubleClickOccured = true;
  16104. clickInfo.doubleClick = true;
  16105. clickInfo.ignore = false;
  16106. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  16107. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16108. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16109. cb(clickInfo, _this._currentPickResult);
  16110. }
  16111. else {
  16112. _this._doubleClickOccured = false;
  16113. _this._previousStartingPointerTime = _this._startingPointerTime;
  16114. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16115. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16116. _this._previousButtonPressed = btn;
  16117. _this._previousHasSwiped = clickInfo.hasSwiped;
  16118. if (Scene.ExclusiveDoubleClickMode) {
  16119. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  16120. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  16121. }
  16122. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  16123. cb(clickInfo, _this._previousPickResult);
  16124. }
  16125. else {
  16126. cb(clickInfo, _this._currentPickResult);
  16127. }
  16128. }
  16129. }
  16130. else {
  16131. _this._doubleClickOccured = false;
  16132. _this._previousStartingPointerTime = _this._startingPointerTime;
  16133. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  16134. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  16135. _this._previousButtonPressed = btn;
  16136. _this._previousHasSwiped = clickInfo.hasSwiped;
  16137. }
  16138. }
  16139. }
  16140. }
  16141. clickInfo.ignore = true;
  16142. cb(clickInfo, _this._currentPickResult);
  16143. };
  16144. var spritePredicate = function (sprite) {
  16145. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  16146. };
  16147. this._onPointerMove = function (evt) {
  16148. _this._updatePointerPosition(evt);
  16149. // PreObservable support
  16150. if (_this.onPrePointerObservable.hasObservers()) {
  16151. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16152. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16153. _this.onPrePointerObservable.notifyObservers(pi, type);
  16154. if (pi.skipOnPointerObservable) {
  16155. return;
  16156. }
  16157. }
  16158. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16159. return;
  16160. }
  16161. var canvas = _this._engine.getRenderingCanvas();
  16162. if (!_this.pointerMovePredicate) {
  16163. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (_this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  16164. }
  16165. // Meshes
  16166. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  16167. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16168. _this.setPointerOverSprite(null);
  16169. _this.setPointerOverMesh(pickResult.pickedMesh);
  16170. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  16171. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  16172. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  16173. }
  16174. else {
  16175. canvas.style.cursor = _this.hoverCursor;
  16176. }
  16177. }
  16178. else {
  16179. canvas.style.cursor = "";
  16180. }
  16181. }
  16182. else {
  16183. _this.setPointerOverMesh(null);
  16184. // Sprites
  16185. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16186. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16187. _this.setPointerOverSprite(pickResult.pickedSprite);
  16188. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  16189. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  16190. }
  16191. else {
  16192. canvas.style.cursor = _this.hoverCursor;
  16193. }
  16194. }
  16195. else {
  16196. _this.setPointerOverSprite(null);
  16197. // Restore pointer
  16198. canvas.style.cursor = "";
  16199. }
  16200. }
  16201. if (_this.onPointerMove) {
  16202. _this.onPointerMove(evt, pickResult);
  16203. }
  16204. if (_this.onPointerObservable.hasObservers()) {
  16205. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16206. var pi = new PointerInfo(type, evt, pickResult);
  16207. _this.onPointerObservable.notifyObservers(pi, type);
  16208. }
  16209. };
  16210. this._onPointerDown = function (evt) {
  16211. _this._isButtonPressed = true;
  16212. _this._pickedDownMesh = null;
  16213. _this._meshPickProceed = false;
  16214. _this._updatePointerPosition(evt);
  16215. // PreObservable support
  16216. if (_this.onPrePointerObservable.hasObservers()) {
  16217. var type = PointerEventTypes.POINTERDOWN;
  16218. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16219. _this.onPrePointerObservable.notifyObservers(pi, type);
  16220. if (pi.skipOnPointerObservable) {
  16221. return;
  16222. }
  16223. }
  16224. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16225. return;
  16226. }
  16227. _this._startingPointerPosition.x = _this._pointerX;
  16228. _this._startingPointerPosition.y = _this._pointerY;
  16229. _this._startingPointerTime = new Date().getTime();
  16230. if (!_this.pointerDownPredicate) {
  16231. _this.pointerDownPredicate = function (mesh) {
  16232. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16233. };
  16234. }
  16235. // Meshes
  16236. _this._pickedDownMesh = null;
  16237. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16238. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16239. _this._pickedDownMesh = pickResult.pickedMesh;
  16240. var actionManager = pickResult.pickedMesh.actionManager;
  16241. if (actionManager) {
  16242. if (actionManager.hasPickTriggers) {
  16243. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16244. switch (evt.button) {
  16245. case 0:
  16246. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16247. break;
  16248. case 1:
  16249. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16250. break;
  16251. case 2:
  16252. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16253. break;
  16254. }
  16255. }
  16256. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  16257. window.setTimeout((function () {
  16258. var _this = this;
  16259. 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);
  16260. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  16261. if (this._isButtonPressed &&
  16262. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  16263. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  16264. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  16265. this._startingPointerTime = 0;
  16266. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16267. }
  16268. }
  16269. }).bind(_this), Scene.LongPressDelay);
  16270. }
  16271. }
  16272. }
  16273. if (_this.onPointerDown) {
  16274. _this.onPointerDown(evt, pickResult);
  16275. }
  16276. if (_this.onPointerObservable.hasObservers()) {
  16277. var type = PointerEventTypes.POINTERDOWN;
  16278. var pi = new PointerInfo(type, evt, pickResult);
  16279. _this.onPointerObservable.notifyObservers(pi, type);
  16280. }
  16281. // Sprites
  16282. _this._pickedDownSprite = null;
  16283. if (_this.spriteManagers.length > 0) {
  16284. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16285. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  16286. if (pickResult.pickedSprite.actionManager) {
  16287. _this._pickedDownSprite = pickResult.pickedSprite;
  16288. switch (evt.button) {
  16289. case 0:
  16290. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16291. break;
  16292. case 1:
  16293. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16294. break;
  16295. case 2:
  16296. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16297. break;
  16298. }
  16299. if (pickResult.pickedSprite.actionManager) {
  16300. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16301. }
  16302. }
  16303. }
  16304. }
  16305. };
  16306. this._onPointerUp = function (evt) {
  16307. _this._isButtonPressed = false;
  16308. _this._pickedUpMesh = null;
  16309. _this._meshPickProceed = false;
  16310. _this._updatePointerPosition(evt);
  16311. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  16312. // PreObservable support
  16313. if (this.onPrePointerObservable.hasObservers()) {
  16314. if (!clickInfo.ignore) {
  16315. if (!clickInfo.hasSwiped) {
  16316. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16317. var type = PointerEventTypes.POINTERTAP;
  16318. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16319. this.onPrePointerObservable.notifyObservers(pi, type);
  16320. if (pi.skipOnPointerObservable) {
  16321. return;
  16322. }
  16323. }
  16324. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16325. var type = PointerEventTypes.POINTERDOUBLETAP;
  16326. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16327. this.onPrePointerObservable.notifyObservers(pi, type);
  16328. if (pi.skipOnPointerObservable) {
  16329. return;
  16330. }
  16331. }
  16332. }
  16333. }
  16334. else {
  16335. var type = PointerEventTypes.POINTERUP;
  16336. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  16337. this.onPrePointerObservable.notifyObservers(pi, type);
  16338. if (pi.skipOnPointerObservable) {
  16339. return;
  16340. }
  16341. }
  16342. }
  16343. if (!this.cameraToUseForPointers && !this.activeCamera) {
  16344. return;
  16345. }
  16346. if (!this.pointerUpPredicate) {
  16347. this.pointerUpPredicate = function (mesh) {
  16348. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  16349. };
  16350. }
  16351. // Meshes
  16352. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  16353. this._initActionManager(null, clickInfo);
  16354. }
  16355. if (!pickResult) {
  16356. pickResult = this._currentPickResult;
  16357. }
  16358. if (pickResult && pickResult && pickResult.pickedMesh) {
  16359. this._pickedUpMesh = pickResult.pickedMesh;
  16360. if (this._pickedDownMesh === this._pickedUpMesh) {
  16361. if (this.onPointerPick) {
  16362. this.onPointerPick(evt, pickResult);
  16363. }
  16364. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  16365. var type = PointerEventTypes.POINTERPICK;
  16366. var pi = new PointerInfo(type, evt, pickResult);
  16367. this.onPointerObservable.notifyObservers(pi, type);
  16368. }
  16369. }
  16370. if (pickResult.pickedMesh.actionManager) {
  16371. if (clickInfo.ignore) {
  16372. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16373. }
  16374. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  16375. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16376. }
  16377. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  16378. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16379. }
  16380. }
  16381. }
  16382. if (this._pickedDownMesh &&
  16383. this._pickedDownMesh.actionManager &&
  16384. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  16385. this._pickedDownMesh !== this._pickedUpMesh) {
  16386. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  16387. }
  16388. if (this.onPointerUp) {
  16389. this.onPointerUp(evt, pickResult);
  16390. }
  16391. if (this.onPointerObservable.hasObservers()) {
  16392. if (!clickInfo.ignore) {
  16393. if (!clickInfo.hasSwiped) {
  16394. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  16395. var type = PointerEventTypes.POINTERTAP;
  16396. var pi = new PointerInfo(type, evt, pickResult);
  16397. this.onPointerObservable.notifyObservers(pi, type);
  16398. }
  16399. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  16400. var type = PointerEventTypes.POINTERDOUBLETAP;
  16401. var pi = new PointerInfo(type, evt, pickResult);
  16402. this.onPointerObservable.notifyObservers(pi, type);
  16403. }
  16404. }
  16405. }
  16406. else {
  16407. var type = PointerEventTypes.POINTERUP;
  16408. var pi = new PointerInfo(type, evt, pickResult);
  16409. this.onPointerObservable.notifyObservers(pi, type);
  16410. }
  16411. }
  16412. // Sprites
  16413. if (this.spriteManagers.length > 0) {
  16414. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  16415. if (pickResult.hit && pickResult.pickedSprite) {
  16416. if (pickResult.pickedSprite.actionManager) {
  16417. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  16418. if (pickResult.pickedSprite.actionManager) {
  16419. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  16420. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  16421. }
  16422. }
  16423. }
  16424. }
  16425. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  16426. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  16427. }
  16428. }
  16429. this._previousPickResult = this._currentPickResult;
  16430. }).bind(_this));
  16431. };
  16432. this._onKeyDown = function (evt) {
  16433. if (_this.actionManager) {
  16434. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16435. }
  16436. };
  16437. this._onKeyUp = function (evt) {
  16438. if (_this.actionManager) {
  16439. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16440. }
  16441. };
  16442. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16443. var canvas = this._engine.getRenderingCanvas();
  16444. if (attachMove) {
  16445. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  16446. // Wheel
  16447. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  16448. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  16449. }
  16450. if (attachDown) {
  16451. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  16452. }
  16453. if (attachUp) {
  16454. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  16455. }
  16456. canvas.tabIndex = 1;
  16457. canvas.addEventListener("keydown", this._onKeyDown, false);
  16458. canvas.addEventListener("keyup", this._onKeyUp, false);
  16459. };
  16460. Scene.prototype.detachControl = function () {
  16461. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16462. var canvas = this._engine.getRenderingCanvas();
  16463. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  16464. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  16465. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  16466. // Wheel
  16467. canvas.removeEventListener('mousewheel', this._onPointerMove);
  16468. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  16469. canvas.removeEventListener("keydown", this._onKeyDown);
  16470. canvas.removeEventListener("keyup", this._onKeyUp);
  16471. };
  16472. // Ready
  16473. Scene.prototype.isReady = function () {
  16474. if (this._pendingData.length > 0) {
  16475. return false;
  16476. }
  16477. var index;
  16478. // Geometries
  16479. for (index = 0; index < this._geometries.length; index++) {
  16480. var geometry = this._geometries[index];
  16481. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  16482. return false;
  16483. }
  16484. }
  16485. // Meshes
  16486. for (index = 0; index < this.meshes.length; index++) {
  16487. var mesh = this.meshes[index];
  16488. if (!mesh.isEnabled()) {
  16489. continue;
  16490. }
  16491. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  16492. continue;
  16493. }
  16494. if (!mesh.isReady()) {
  16495. return false;
  16496. }
  16497. var mat = mesh.material;
  16498. if (mat) {
  16499. if (!mat.isReady(mesh)) {
  16500. return false;
  16501. }
  16502. }
  16503. }
  16504. return true;
  16505. };
  16506. Scene.prototype.resetCachedMaterial = function () {
  16507. this._cachedMaterial = null;
  16508. this._cachedEffect = null;
  16509. this._cachedVisibility = null;
  16510. };
  16511. Scene.prototype.registerBeforeRender = function (func) {
  16512. this.onBeforeRenderObservable.add(func);
  16513. };
  16514. Scene.prototype.unregisterBeforeRender = function (func) {
  16515. this.onBeforeRenderObservable.removeCallback(func);
  16516. };
  16517. Scene.prototype.registerAfterRender = function (func) {
  16518. this.onAfterRenderObservable.add(func);
  16519. };
  16520. Scene.prototype.unregisterAfterRender = function (func) {
  16521. this.onAfterRenderObservable.removeCallback(func);
  16522. };
  16523. Scene.prototype._addPendingData = function (data) {
  16524. this._pendingData.push(data);
  16525. };
  16526. Scene.prototype._removePendingData = function (data) {
  16527. var index = this._pendingData.indexOf(data);
  16528. if (index !== -1) {
  16529. this._pendingData.splice(index, 1);
  16530. }
  16531. };
  16532. Scene.prototype.getWaitingItemsCount = function () {
  16533. return this._pendingData.length;
  16534. };
  16535. /**
  16536. * Registers a function to be executed when the scene is ready.
  16537. * @param {Function} func - the function to be executed.
  16538. */
  16539. Scene.prototype.executeWhenReady = function (func) {
  16540. var _this = this;
  16541. this.onReadyObservable.add(func);
  16542. if (this._executeWhenReadyTimeoutId !== -1) {
  16543. return;
  16544. }
  16545. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16546. _this._checkIsReady();
  16547. }, 150);
  16548. };
  16549. Scene.prototype._checkIsReady = function () {
  16550. var _this = this;
  16551. if (this.isReady()) {
  16552. this.onReadyObservable.notifyObservers(this);
  16553. this.onReadyObservable.clear();
  16554. this._executeWhenReadyTimeoutId = -1;
  16555. return;
  16556. }
  16557. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16558. _this._checkIsReady();
  16559. }, 150);
  16560. };
  16561. // Animations
  16562. /**
  16563. * Will start the animation sequence of a given target
  16564. * @param target - the target
  16565. * @param {number} from - from which frame should animation start
  16566. * @param {number} to - till which frame should animation run.
  16567. * @param {boolean} [loop] - should the animation loop
  16568. * @param {number} [speedRatio] - the speed in which to run the animation
  16569. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  16570. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  16571. * @return {BABYLON.Animatable} the animatable object created for this animation
  16572. * @see BABYLON.Animatable
  16573. * @see http://doc.babylonjs.com/page.php?p=22081
  16574. */
  16575. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  16576. if (speedRatio === void 0) { speedRatio = 1.0; }
  16577. this.stopAnimation(target);
  16578. if (!animatable) {
  16579. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  16580. }
  16581. // Local animations
  16582. if (target.animations) {
  16583. animatable.appendAnimations(target, target.animations);
  16584. }
  16585. // Children animations
  16586. if (target.getAnimatables) {
  16587. var animatables = target.getAnimatables();
  16588. for (var index = 0; index < animatables.length; index++) {
  16589. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  16590. }
  16591. }
  16592. animatable.reset();
  16593. return animatable;
  16594. };
  16595. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  16596. if (speedRatio === undefined) {
  16597. speedRatio = 1.0;
  16598. }
  16599. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  16600. return animatable;
  16601. };
  16602. Scene.prototype.getAnimatableByTarget = function (target) {
  16603. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16604. if (this._activeAnimatables[index].target === target) {
  16605. return this._activeAnimatables[index];
  16606. }
  16607. }
  16608. return null;
  16609. };
  16610. Object.defineProperty(Scene.prototype, "Animatables", {
  16611. get: function () {
  16612. return this._activeAnimatables;
  16613. },
  16614. enumerable: true,
  16615. configurable: true
  16616. });
  16617. /**
  16618. * Will stop the animation of the given target
  16619. * @param target - the target
  16620. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  16621. * @see beginAnimation
  16622. */
  16623. Scene.prototype.stopAnimation = function (target, animationName) {
  16624. var animatable = this.getAnimatableByTarget(target);
  16625. if (animatable) {
  16626. animatable.stop(animationName);
  16627. }
  16628. };
  16629. Scene.prototype._animate = function () {
  16630. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  16631. return;
  16632. }
  16633. // Getting time
  16634. var now = BABYLON.Tools.Now;
  16635. if (!this._animationTimeLast) {
  16636. if (this._pendingData.length > 0) {
  16637. return;
  16638. }
  16639. this._animationTimeLast = now;
  16640. }
  16641. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  16642. this._animationTime += deltaTime;
  16643. this._animationTimeLast = now;
  16644. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16645. this._activeAnimatables[index]._animate(this._animationTime);
  16646. }
  16647. };
  16648. // Matrix
  16649. Scene.prototype.getViewMatrix = function () {
  16650. return this._viewMatrix;
  16651. };
  16652. Scene.prototype.getProjectionMatrix = function () {
  16653. return this._projectionMatrix;
  16654. };
  16655. Scene.prototype.getTransformMatrix = function () {
  16656. return this._transformMatrix;
  16657. };
  16658. Scene.prototype.setTransformMatrix = function (view, projection) {
  16659. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  16660. return;
  16661. }
  16662. this._viewUpdateFlag = view.updateFlag;
  16663. this._projectionUpdateFlag = projection.updateFlag;
  16664. this._viewMatrix = view;
  16665. this._projectionMatrix = projection;
  16666. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16667. // Update frustum
  16668. if (!this._frustumPlanes) {
  16669. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16670. }
  16671. else {
  16672. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16673. }
  16674. if (this._sceneUbo.useUbo) {
  16675. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  16676. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  16677. this._sceneUbo.update();
  16678. }
  16679. };
  16680. Scene.prototype.getSceneUniformBuffer = function () {
  16681. return this._sceneUbo;
  16682. };
  16683. // Methods
  16684. Scene.prototype.getUniqueId = function () {
  16685. var result = this._uniqueIdCounter;
  16686. this._uniqueIdCounter++;
  16687. return result;
  16688. };
  16689. Scene.prototype.addMesh = function (newMesh) {
  16690. newMesh.uniqueId = this.getUniqueId();
  16691. var position = this.meshes.push(newMesh);
  16692. //notify the collision coordinator
  16693. if (this.collisionCoordinator) {
  16694. this.collisionCoordinator.onMeshAdded(newMesh);
  16695. }
  16696. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  16697. };
  16698. Scene.prototype.removeMesh = function (toRemove) {
  16699. var index = this.meshes.indexOf(toRemove);
  16700. if (index !== -1) {
  16701. // Remove from the scene if mesh found
  16702. this.meshes.splice(index, 1);
  16703. }
  16704. //notify the collision coordinator
  16705. if (this.collisionCoordinator) {
  16706. this.collisionCoordinator.onMeshRemoved(toRemove);
  16707. }
  16708. this.onMeshRemovedObservable.notifyObservers(toRemove);
  16709. return index;
  16710. };
  16711. Scene.prototype.removeSkeleton = function (toRemove) {
  16712. var index = this.skeletons.indexOf(toRemove);
  16713. if (index !== -1) {
  16714. // Remove from the scene if found
  16715. this.skeletons.splice(index, 1);
  16716. }
  16717. return index;
  16718. };
  16719. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  16720. var index = this.morphTargetManagers.indexOf(toRemove);
  16721. if (index !== -1) {
  16722. // Remove from the scene if found
  16723. this.morphTargetManagers.splice(index, 1);
  16724. }
  16725. return index;
  16726. };
  16727. Scene.prototype.removeLight = function (toRemove) {
  16728. var index = this.lights.indexOf(toRemove);
  16729. if (index !== -1) {
  16730. // Remove from the scene if mesh found
  16731. this.lights.splice(index, 1);
  16732. this.sortLightsByPriority();
  16733. }
  16734. this.onLightRemovedObservable.notifyObservers(toRemove);
  16735. return index;
  16736. };
  16737. Scene.prototype.removeCamera = function (toRemove) {
  16738. var index = this.cameras.indexOf(toRemove);
  16739. if (index !== -1) {
  16740. // Remove from the scene if mesh found
  16741. this.cameras.splice(index, 1);
  16742. }
  16743. // Remove from activeCameras
  16744. var index2 = this.activeCameras.indexOf(toRemove);
  16745. if (index2 !== -1) {
  16746. // Remove from the scene if mesh found
  16747. this.activeCameras.splice(index2, 1);
  16748. }
  16749. // Reset the activeCamera
  16750. if (this.activeCamera === toRemove) {
  16751. if (this.cameras.length > 0) {
  16752. this.activeCamera = this.cameras[0];
  16753. }
  16754. else {
  16755. this.activeCamera = null;
  16756. }
  16757. }
  16758. this.onCameraRemovedObservable.notifyObservers(toRemove);
  16759. return index;
  16760. };
  16761. Scene.prototype.addLight = function (newLight) {
  16762. newLight.uniqueId = this.getUniqueId();
  16763. this.lights.push(newLight);
  16764. this.sortLightsByPriority();
  16765. this.onNewLightAddedObservable.notifyObservers(newLight);
  16766. };
  16767. Scene.prototype.sortLightsByPriority = function () {
  16768. if (this.requireLightSorting) {
  16769. this.lights.sort(BABYLON.Light.compareLightsPriority);
  16770. }
  16771. };
  16772. Scene.prototype.addCamera = function (newCamera) {
  16773. newCamera.uniqueId = this.getUniqueId();
  16774. var position = this.cameras.push(newCamera);
  16775. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  16776. };
  16777. /**
  16778. * Switch active camera
  16779. * @param {Camera} newCamera - new active camera
  16780. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  16781. */
  16782. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  16783. if (attachControl === void 0) { attachControl = true; }
  16784. var canvas = this._engine.getRenderingCanvas();
  16785. this.activeCamera.detachControl(canvas);
  16786. this.activeCamera = newCamera;
  16787. if (attachControl) {
  16788. newCamera.attachControl(canvas);
  16789. }
  16790. };
  16791. /**
  16792. * sets the active camera of the scene using its ID
  16793. * @param {string} id - the camera's ID
  16794. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16795. * @see activeCamera
  16796. */
  16797. Scene.prototype.setActiveCameraByID = function (id) {
  16798. var camera = this.getCameraByID(id);
  16799. if (camera) {
  16800. this.activeCamera = camera;
  16801. return camera;
  16802. }
  16803. return null;
  16804. };
  16805. /**
  16806. * sets the active camera of the scene using its name
  16807. * @param {string} name - the camera's name
  16808. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16809. * @see activeCamera
  16810. */
  16811. Scene.prototype.setActiveCameraByName = function (name) {
  16812. var camera = this.getCameraByName(name);
  16813. if (camera) {
  16814. this.activeCamera = camera;
  16815. return camera;
  16816. }
  16817. return null;
  16818. };
  16819. /**
  16820. * get a material using its id
  16821. * @param {string} the material's ID
  16822. * @return {BABYLON.Material|null} the material or null if none found.
  16823. */
  16824. Scene.prototype.getMaterialByID = function (id) {
  16825. for (var index = 0; index < this.materials.length; index++) {
  16826. if (this.materials[index].id === id) {
  16827. return this.materials[index];
  16828. }
  16829. }
  16830. return null;
  16831. };
  16832. /**
  16833. * get a material using its name
  16834. * @param {string} the material's name
  16835. * @return {BABYLON.Material|null} the material or null if none found.
  16836. */
  16837. Scene.prototype.getMaterialByName = function (name) {
  16838. for (var index = 0; index < this.materials.length; index++) {
  16839. if (this.materials[index].name === name) {
  16840. return this.materials[index];
  16841. }
  16842. }
  16843. return null;
  16844. };
  16845. Scene.prototype.getLensFlareSystemByName = function (name) {
  16846. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16847. if (this.lensFlareSystems[index].name === name) {
  16848. return this.lensFlareSystems[index];
  16849. }
  16850. }
  16851. return null;
  16852. };
  16853. Scene.prototype.getLensFlareSystemByID = function (id) {
  16854. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16855. if (this.lensFlareSystems[index].id === id) {
  16856. return this.lensFlareSystems[index];
  16857. }
  16858. }
  16859. return null;
  16860. };
  16861. Scene.prototype.getCameraByID = function (id) {
  16862. for (var index = 0; index < this.cameras.length; index++) {
  16863. if (this.cameras[index].id === id) {
  16864. return this.cameras[index];
  16865. }
  16866. }
  16867. return null;
  16868. };
  16869. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  16870. for (var index = 0; index < this.cameras.length; index++) {
  16871. if (this.cameras[index].uniqueId === uniqueId) {
  16872. return this.cameras[index];
  16873. }
  16874. }
  16875. return null;
  16876. };
  16877. /**
  16878. * get a camera using its name
  16879. * @param {string} the camera's name
  16880. * @return {BABYLON.Camera|null} the camera or null if none found.
  16881. */
  16882. Scene.prototype.getCameraByName = function (name) {
  16883. for (var index = 0; index < this.cameras.length; index++) {
  16884. if (this.cameras[index].name === name) {
  16885. return this.cameras[index];
  16886. }
  16887. }
  16888. return null;
  16889. };
  16890. /**
  16891. * get a bone using its id
  16892. * @param {string} the bone's id
  16893. * @return {BABYLON.Bone|null} the bone or null if not found
  16894. */
  16895. Scene.prototype.getBoneByID = function (id) {
  16896. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16897. var skeleton = this.skeletons[skeletonIndex];
  16898. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16899. if (skeleton.bones[boneIndex].id === id) {
  16900. return skeleton.bones[boneIndex];
  16901. }
  16902. }
  16903. }
  16904. return null;
  16905. };
  16906. /**
  16907. * get a bone using its id
  16908. * @param {string} the bone's name
  16909. * @return {BABYLON.Bone|null} the bone or null if not found
  16910. */
  16911. Scene.prototype.getBoneByName = function (name) {
  16912. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16913. var skeleton = this.skeletons[skeletonIndex];
  16914. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16915. if (skeleton.bones[boneIndex].name === name) {
  16916. return skeleton.bones[boneIndex];
  16917. }
  16918. }
  16919. }
  16920. return null;
  16921. };
  16922. /**
  16923. * get a light node using its name
  16924. * @param {string} the light's name
  16925. * @return {BABYLON.Light|null} the light or null if none found.
  16926. */
  16927. Scene.prototype.getLightByName = function (name) {
  16928. for (var index = 0; index < this.lights.length; index++) {
  16929. if (this.lights[index].name === name) {
  16930. return this.lights[index];
  16931. }
  16932. }
  16933. return null;
  16934. };
  16935. /**
  16936. * get a light node using its ID
  16937. * @param {string} the light's id
  16938. * @return {BABYLON.Light|null} the light or null if none found.
  16939. */
  16940. Scene.prototype.getLightByID = function (id) {
  16941. for (var index = 0; index < this.lights.length; index++) {
  16942. if (this.lights[index].id === id) {
  16943. return this.lights[index];
  16944. }
  16945. }
  16946. return null;
  16947. };
  16948. /**
  16949. * get a light node using its scene-generated unique ID
  16950. * @param {number} the light's unique id
  16951. * @return {BABYLON.Light|null} the light or null if none found.
  16952. */
  16953. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  16954. for (var index = 0; index < this.lights.length; index++) {
  16955. if (this.lights[index].uniqueId === uniqueId) {
  16956. return this.lights[index];
  16957. }
  16958. }
  16959. return null;
  16960. };
  16961. /**
  16962. * get a particle system by id
  16963. * @param id {number} the particle system id
  16964. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  16965. */
  16966. Scene.prototype.getParticleSystemByID = function (id) {
  16967. for (var index = 0; index < this.particleSystems.length; index++) {
  16968. if (this.particleSystems[index].id === id) {
  16969. return this.particleSystems[index];
  16970. }
  16971. }
  16972. return null;
  16973. };
  16974. /**
  16975. * get a geometry using its ID
  16976. * @param {string} the geometry's id
  16977. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  16978. */
  16979. Scene.prototype.getGeometryByID = function (id) {
  16980. for (var index = 0; index < this._geometries.length; index++) {
  16981. if (this._geometries[index].id === id) {
  16982. return this._geometries[index];
  16983. }
  16984. }
  16985. return null;
  16986. };
  16987. /**
  16988. * add a new geometry to this scene.
  16989. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  16990. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  16991. * @return {boolean} was the geometry added or not
  16992. */
  16993. Scene.prototype.pushGeometry = function (geometry, force) {
  16994. if (!force && this.getGeometryByID(geometry.id)) {
  16995. return false;
  16996. }
  16997. this._geometries.push(geometry);
  16998. //notify the collision coordinator
  16999. if (this.collisionCoordinator) {
  17000. this.collisionCoordinator.onGeometryAdded(geometry);
  17001. }
  17002. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17003. return true;
  17004. };
  17005. /**
  17006. * Removes an existing geometry
  17007. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17008. * @return {boolean} was the geometry removed or not
  17009. */
  17010. Scene.prototype.removeGeometry = function (geometry) {
  17011. var index = this._geometries.indexOf(geometry);
  17012. if (index > -1) {
  17013. this._geometries.splice(index, 1);
  17014. //notify the collision coordinator
  17015. if (this.collisionCoordinator) {
  17016. this.collisionCoordinator.onGeometryDeleted(geometry);
  17017. }
  17018. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17019. return true;
  17020. }
  17021. return false;
  17022. };
  17023. Scene.prototype.getGeometries = function () {
  17024. return this._geometries;
  17025. };
  17026. /**
  17027. * Get the first added mesh found of a given ID
  17028. * @param {string} id - the id to search for
  17029. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17030. */
  17031. Scene.prototype.getMeshByID = function (id) {
  17032. for (var index = 0; index < this.meshes.length; index++) {
  17033. if (this.meshes[index].id === id) {
  17034. return this.meshes[index];
  17035. }
  17036. }
  17037. return null;
  17038. };
  17039. Scene.prototype.getMeshesByID = function (id) {
  17040. return this.meshes.filter(function (m) {
  17041. return m.id === id;
  17042. });
  17043. };
  17044. /**
  17045. * Get a mesh with its auto-generated unique id
  17046. * @param {number} uniqueId - the unique id to search for
  17047. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17048. */
  17049. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  17050. for (var index = 0; index < this.meshes.length; index++) {
  17051. if (this.meshes[index].uniqueId === uniqueId) {
  17052. return this.meshes[index];
  17053. }
  17054. }
  17055. return null;
  17056. };
  17057. /**
  17058. * Get a the last added mesh found of a given ID
  17059. * @param {string} id - the id to search for
  17060. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17061. */
  17062. Scene.prototype.getLastMeshByID = function (id) {
  17063. for (var index = this.meshes.length - 1; index >= 0; index--) {
  17064. if (this.meshes[index].id === id) {
  17065. return this.meshes[index];
  17066. }
  17067. }
  17068. return null;
  17069. };
  17070. /**
  17071. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  17072. * @param {string} id - the id to search for
  17073. * @return {BABYLON.Node|null} the node found or null if not found at all.
  17074. */
  17075. Scene.prototype.getLastEntryByID = function (id) {
  17076. var index;
  17077. for (index = this.meshes.length - 1; index >= 0; index--) {
  17078. if (this.meshes[index].id === id) {
  17079. return this.meshes[index];
  17080. }
  17081. }
  17082. for (index = this.cameras.length - 1; index >= 0; index--) {
  17083. if (this.cameras[index].id === id) {
  17084. return this.cameras[index];
  17085. }
  17086. }
  17087. for (index = this.lights.length - 1; index >= 0; index--) {
  17088. if (this.lights[index].id === id) {
  17089. return this.lights[index];
  17090. }
  17091. }
  17092. return null;
  17093. };
  17094. Scene.prototype.getNodeByID = function (id) {
  17095. var mesh = this.getMeshByID(id);
  17096. if (mesh) {
  17097. return mesh;
  17098. }
  17099. var light = this.getLightByID(id);
  17100. if (light) {
  17101. return light;
  17102. }
  17103. var camera = this.getCameraByID(id);
  17104. if (camera) {
  17105. return camera;
  17106. }
  17107. var bone = this.getBoneByID(id);
  17108. return bone;
  17109. };
  17110. Scene.prototype.getNodeByName = function (name) {
  17111. var mesh = this.getMeshByName(name);
  17112. if (mesh) {
  17113. return mesh;
  17114. }
  17115. var light = this.getLightByName(name);
  17116. if (light) {
  17117. return light;
  17118. }
  17119. var camera = this.getCameraByName(name);
  17120. if (camera) {
  17121. return camera;
  17122. }
  17123. var bone = this.getBoneByName(name);
  17124. return bone;
  17125. };
  17126. Scene.prototype.getMeshByName = function (name) {
  17127. for (var index = 0; index < this.meshes.length; index++) {
  17128. if (this.meshes[index].name === name) {
  17129. return this.meshes[index];
  17130. }
  17131. }
  17132. return null;
  17133. };
  17134. Scene.prototype.getSoundByName = function (name) {
  17135. var index;
  17136. if (BABYLON.AudioEngine) {
  17137. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  17138. if (this.mainSoundTrack.soundCollection[index].name === name) {
  17139. return this.mainSoundTrack.soundCollection[index];
  17140. }
  17141. }
  17142. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  17143. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  17144. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  17145. return this.soundTracks[sdIndex].soundCollection[index];
  17146. }
  17147. }
  17148. }
  17149. }
  17150. return null;
  17151. };
  17152. Scene.prototype.getLastSkeletonByID = function (id) {
  17153. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  17154. if (this.skeletons[index].id === id) {
  17155. return this.skeletons[index];
  17156. }
  17157. }
  17158. return null;
  17159. };
  17160. Scene.prototype.getSkeletonById = function (id) {
  17161. for (var index = 0; index < this.skeletons.length; index++) {
  17162. if (this.skeletons[index].id === id) {
  17163. return this.skeletons[index];
  17164. }
  17165. }
  17166. return null;
  17167. };
  17168. Scene.prototype.getSkeletonByName = function (name) {
  17169. for (var index = 0; index < this.skeletons.length; index++) {
  17170. if (this.skeletons[index].name === name) {
  17171. return this.skeletons[index];
  17172. }
  17173. }
  17174. return null;
  17175. };
  17176. Scene.prototype.getMorphTargetManagerById = function (id) {
  17177. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  17178. if (this.morphTargetManagers[index].uniqueId === id) {
  17179. return this.morphTargetManagers[index];
  17180. }
  17181. }
  17182. return null;
  17183. };
  17184. Scene.prototype.isActiveMesh = function (mesh) {
  17185. return (this._activeMeshes.indexOf(mesh) !== -1);
  17186. };
  17187. /**
  17188. * Return a the first highlight layer of the scene with a given name.
  17189. * @param name The name of the highlight layer to look for.
  17190. * @return The highlight layer if found otherwise null.
  17191. */
  17192. Scene.prototype.getHighlightLayerByName = function (name) {
  17193. for (var index = 0; index < this.highlightLayers.length; index++) {
  17194. if (this.highlightLayers[index].name === name) {
  17195. return this.highlightLayers[index];
  17196. }
  17197. }
  17198. return null;
  17199. };
  17200. Object.defineProperty(Scene.prototype, "uid", {
  17201. /**
  17202. * Return a unique id as a string which can serve as an identifier for the scene
  17203. */
  17204. get: function () {
  17205. if (!this._uid) {
  17206. this._uid = BABYLON.Tools.RandomId();
  17207. }
  17208. return this._uid;
  17209. },
  17210. enumerable: true,
  17211. configurable: true
  17212. });
  17213. /**
  17214. * Add an externaly attached data from its key.
  17215. * This method call will fail and return false, if such key already exists.
  17216. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17217. * @param key the unique key that identifies the data
  17218. * @param data the data object to associate to the key for this Engine instance
  17219. * @return true if no such key were already present and the data was added successfully, false otherwise
  17220. */
  17221. Scene.prototype.addExternalData = function (key, data) {
  17222. if (!this._externalData) {
  17223. this._externalData = new BABYLON.StringDictionary();
  17224. }
  17225. return this._externalData.add(key, data);
  17226. };
  17227. /**
  17228. * Get an externaly attached data from its key
  17229. * @param key the unique key that identifies the data
  17230. * @return the associated data, if present (can be null), or undefined if not present
  17231. */
  17232. Scene.prototype.getExternalData = function (key) {
  17233. if (!this._externalData) {
  17234. return null;
  17235. }
  17236. return this._externalData.get(key);
  17237. };
  17238. /**
  17239. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17240. * @param key the unique key that identifies the data
  17241. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17242. * @return the associated data, can be null if the factory returned null.
  17243. */
  17244. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17245. if (!this._externalData) {
  17246. this._externalData = new BABYLON.StringDictionary();
  17247. }
  17248. return this._externalData.getOrAddWithFactory(key, factory);
  17249. };
  17250. /**
  17251. * Remove an externaly attached data from the Engine instance
  17252. * @param key the unique key that identifies the data
  17253. * @return true if the data was successfully removed, false if it doesn't exist
  17254. */
  17255. Scene.prototype.removeExternalData = function (key) {
  17256. return this._externalData.remove(key);
  17257. };
  17258. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  17259. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  17260. var material = subMesh.getMaterial();
  17261. if (mesh.showSubMeshesBoundingBox) {
  17262. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  17263. }
  17264. if (material) {
  17265. // Render targets
  17266. if (material.getRenderTargetTextures) {
  17267. if (this._processedMaterials.indexOf(material) === -1) {
  17268. this._processedMaterials.push(material);
  17269. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  17270. }
  17271. }
  17272. // Dispatch
  17273. this._activeIndices.addCount(subMesh.indexCount, false);
  17274. this._renderingManager.dispatch(subMesh);
  17275. }
  17276. }
  17277. };
  17278. Scene.prototype._isInIntermediateRendering = function () {
  17279. return this._intermediateRendering;
  17280. };
  17281. Scene.prototype._evaluateActiveMeshes = function () {
  17282. this.activeCamera._activeMeshes.reset();
  17283. this._activeMeshes.reset();
  17284. this._renderingManager.reset();
  17285. this._processedMaterials.reset();
  17286. this._activeParticleSystems.reset();
  17287. this._activeSkeletons.reset();
  17288. this._softwareSkinnedMeshes.reset();
  17289. if (this._boundingBoxRenderer) {
  17290. this._boundingBoxRenderer.reset();
  17291. }
  17292. // Meshes
  17293. var meshes;
  17294. var len;
  17295. if (this._selectionOctree) {
  17296. var selection = this._selectionOctree.select(this._frustumPlanes);
  17297. meshes = selection.data;
  17298. len = selection.length;
  17299. }
  17300. else {
  17301. len = this.meshes.length;
  17302. meshes = this.meshes;
  17303. }
  17304. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  17305. var mesh = meshes[meshIndex];
  17306. if (mesh.isBlocked) {
  17307. continue;
  17308. }
  17309. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  17310. if (!mesh.isReady() || !mesh.isEnabled()) {
  17311. continue;
  17312. }
  17313. mesh.computeWorldMatrix();
  17314. // Intersections
  17315. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  17316. this._meshesForIntersections.pushNoDuplicate(mesh);
  17317. }
  17318. // Switch to current LOD
  17319. var meshLOD = mesh.getLOD(this.activeCamera);
  17320. if (!meshLOD) {
  17321. continue;
  17322. }
  17323. mesh._preActivate();
  17324. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  17325. this._activeMeshes.push(mesh);
  17326. this.activeCamera._activeMeshes.push(mesh);
  17327. mesh._activate(this._renderId);
  17328. this._activeMesh(mesh, meshLOD);
  17329. }
  17330. }
  17331. // Particle systems
  17332. this._particlesDuration.beginMonitoring();
  17333. var beforeParticlesDate = BABYLON.Tools.Now;
  17334. if (this.particlesEnabled) {
  17335. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  17336. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  17337. var particleSystem = this.particleSystems[particleIndex];
  17338. if (!particleSystem.isStarted()) {
  17339. continue;
  17340. }
  17341. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  17342. this._activeParticleSystems.push(particleSystem);
  17343. particleSystem.animate();
  17344. this._renderingManager.dispatchParticles(particleSystem);
  17345. }
  17346. }
  17347. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  17348. }
  17349. this._particlesDuration.endMonitoring(false);
  17350. };
  17351. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  17352. if (mesh.skeleton && this.skeletonsEnabled) {
  17353. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  17354. mesh.skeleton.prepare();
  17355. }
  17356. if (!mesh.computeBonesUsingShaders) {
  17357. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  17358. }
  17359. }
  17360. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  17361. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  17362. }
  17363. if (mesh && mesh.subMeshes) {
  17364. // Submeshes Octrees
  17365. var len;
  17366. var subMeshes;
  17367. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  17368. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  17369. len = intersections.length;
  17370. subMeshes = intersections.data;
  17371. }
  17372. else {
  17373. subMeshes = mesh.subMeshes;
  17374. len = subMeshes.length;
  17375. }
  17376. for (var subIndex = 0; subIndex < len; subIndex++) {
  17377. var subMesh = subMeshes[subIndex];
  17378. this._evaluateSubMesh(subMesh, mesh);
  17379. }
  17380. }
  17381. };
  17382. Scene.prototype.updateTransformMatrix = function (force) {
  17383. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  17384. };
  17385. Scene.prototype._renderForCamera = function (camera) {
  17386. var engine = this._engine;
  17387. var startTime = BABYLON.Tools.Now;
  17388. this.activeCamera = camera;
  17389. if (!this.activeCamera)
  17390. throw new Error("Active camera not set");
  17391. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17392. // Viewport
  17393. engine.setViewport(this.activeCamera.viewport);
  17394. // Camera
  17395. this.resetCachedMaterial();
  17396. this._renderId++;
  17397. this.updateTransformMatrix();
  17398. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  17399. // Meshes
  17400. this._evaluateActiveMeshesDuration.beginMonitoring();
  17401. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  17402. this._evaluateActiveMeshes();
  17403. this._evaluateActiveMeshesDuration.endMonitoring(false);
  17404. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  17405. // Software skinning
  17406. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  17407. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  17408. mesh.applySkeleton(mesh.skeleton);
  17409. }
  17410. // Render targets
  17411. this._renderTargetsDuration.beginMonitoring();
  17412. var needsRestoreFrameBuffer = false;
  17413. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17414. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  17415. this._intermediateRendering = true;
  17416. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17417. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  17418. var renderTarget = this._renderTargets.data[renderIndex];
  17419. if (renderTarget._shouldRender()) {
  17420. this._renderId++;
  17421. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  17422. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  17423. }
  17424. }
  17425. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17426. this._intermediateRendering = false;
  17427. this._renderId++;
  17428. needsRestoreFrameBuffer = true; // Restore back buffer
  17429. }
  17430. // Render HighlightLayer Texture
  17431. var stencilState = this._engine.getStencilBuffer();
  17432. var renderhighlights = false;
  17433. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  17434. this._intermediateRendering = true;
  17435. for (var i = 0; i < this.highlightLayers.length; i++) {
  17436. var highlightLayer = this.highlightLayers[i];
  17437. if (highlightLayer.shouldRender() &&
  17438. (!highlightLayer.camera ||
  17439. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  17440. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  17441. renderhighlights = true;
  17442. var renderTarget = highlightLayer._mainTexture;
  17443. if (renderTarget._shouldRender()) {
  17444. this._renderId++;
  17445. renderTarget.render(false, false);
  17446. needsRestoreFrameBuffer = true;
  17447. }
  17448. }
  17449. }
  17450. this._intermediateRendering = false;
  17451. this._renderId++;
  17452. }
  17453. if (needsRestoreFrameBuffer) {
  17454. if (this.offscreenRenderTarget) {
  17455. engine.bindFramebuffer(this.offscreenRenderTarget._texture);
  17456. }
  17457. else {
  17458. engine.restoreDefaultFramebuffer(); // Restore back buffer
  17459. }
  17460. }
  17461. this._renderTargetsDuration.endMonitoring(false);
  17462. // Prepare Frame
  17463. this.postProcessManager._prepareFrame();
  17464. this._renderDuration.beginMonitoring();
  17465. // Backgrounds
  17466. var layerIndex;
  17467. var layer;
  17468. if (this.layers.length) {
  17469. engine.setDepthBuffer(false);
  17470. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17471. layer = this.layers[layerIndex];
  17472. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  17473. layer.render();
  17474. }
  17475. }
  17476. engine.setDepthBuffer(true);
  17477. }
  17478. // Render
  17479. BABYLON.Tools.StartPerformanceCounter("Main render");
  17480. // Activate HighlightLayer stencil
  17481. if (renderhighlights) {
  17482. this._engine.setStencilBuffer(true);
  17483. }
  17484. this._renderingManager.render(null, null, true, true);
  17485. // Restore HighlightLayer stencil
  17486. if (renderhighlights) {
  17487. this._engine.setStencilBuffer(stencilState);
  17488. }
  17489. BABYLON.Tools.EndPerformanceCounter("Main render");
  17490. // Bounding boxes
  17491. if (this._boundingBoxRenderer) {
  17492. this._boundingBoxRenderer.render();
  17493. }
  17494. // Lens flares
  17495. if (this.lensFlaresEnabled) {
  17496. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17497. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  17498. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  17499. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  17500. lensFlareSystem.render();
  17501. }
  17502. }
  17503. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17504. }
  17505. // Foregrounds
  17506. if (this.layers.length) {
  17507. engine.setDepthBuffer(false);
  17508. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17509. layer = this.layers[layerIndex];
  17510. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  17511. layer.render();
  17512. }
  17513. }
  17514. engine.setDepthBuffer(true);
  17515. }
  17516. // Highlight Layer
  17517. if (renderhighlights) {
  17518. engine.setDepthBuffer(false);
  17519. for (var i = 0; i < this.highlightLayers.length; i++) {
  17520. if (this.highlightLayers[i].shouldRender()) {
  17521. this.highlightLayers[i].render();
  17522. }
  17523. }
  17524. engine.setDepthBuffer(true);
  17525. }
  17526. this._renderDuration.endMonitoring(false);
  17527. // Finalize frame
  17528. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  17529. // Update camera
  17530. this.activeCamera._updateFromScene();
  17531. // Reset some special arrays
  17532. this._renderTargets.reset();
  17533. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  17534. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17535. };
  17536. Scene.prototype._processSubCameras = function (camera) {
  17537. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  17538. this._renderForCamera(camera);
  17539. return;
  17540. }
  17541. // rig cameras
  17542. for (var index = 0; index < camera._rigCameras.length; index++) {
  17543. this._renderForCamera(camera._rigCameras[index]);
  17544. }
  17545. this.activeCamera = camera;
  17546. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  17547. // Update camera
  17548. this.activeCamera._updateFromScene();
  17549. };
  17550. Scene.prototype._checkIntersections = function () {
  17551. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  17552. var sourceMesh = this._meshesForIntersections.data[index];
  17553. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  17554. var action = sourceMesh.actionManager.actions[actionIndex];
  17555. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17556. var parameters = action.getTriggerParameter();
  17557. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  17558. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  17559. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  17560. if (areIntersecting && currentIntersectionInProgress === -1) {
  17561. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  17562. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17563. sourceMesh._intersectionsInProgress.push(otherMesh);
  17564. }
  17565. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17566. sourceMesh._intersectionsInProgress.push(otherMesh);
  17567. }
  17568. }
  17569. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  17570. //They intersected, and now they don't.
  17571. //is this trigger an exit trigger? execute an event.
  17572. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17573. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17574. }
  17575. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  17576. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17577. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  17578. }
  17579. }
  17580. }
  17581. }
  17582. }
  17583. };
  17584. Scene.prototype.render = function () {
  17585. if (this.isDisposed) {
  17586. return;
  17587. }
  17588. this._lastFrameDuration.beginMonitoring();
  17589. this._particlesDuration.fetchNewFrame();
  17590. this._spritesDuration.fetchNewFrame();
  17591. this._activeParticles.fetchNewFrame();
  17592. this._renderDuration.fetchNewFrame();
  17593. this._renderTargetsDuration.fetchNewFrame();
  17594. this._evaluateActiveMeshesDuration.fetchNewFrame();
  17595. this._totalVertices.fetchNewFrame();
  17596. this._activeIndices.fetchNewFrame();
  17597. this._activeBones.fetchNewFrame();
  17598. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  17599. this._meshesForIntersections.reset();
  17600. this.resetCachedMaterial();
  17601. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  17602. // Actions
  17603. if (this.actionManager) {
  17604. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  17605. }
  17606. //Simplification Queue
  17607. if (this.simplificationQueue && !this.simplificationQueue.running) {
  17608. this.simplificationQueue.executeNext();
  17609. }
  17610. // Animations
  17611. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  17612. this._animationRatio = deltaTime * (60.0 / 1000.0);
  17613. this._animate();
  17614. // Physics
  17615. if (this._physicsEngine) {
  17616. BABYLON.Tools.StartPerformanceCounter("Physics");
  17617. this._physicsEngine._step(deltaTime / 1000.0);
  17618. BABYLON.Tools.EndPerformanceCounter("Physics");
  17619. }
  17620. // Before render
  17621. this.onBeforeRenderObservable.notifyObservers(this);
  17622. // Customs render targets
  17623. this._renderTargetsDuration.beginMonitoring();
  17624. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17625. var engine = this.getEngine();
  17626. var currentActiveCamera = this.activeCamera;
  17627. if (this.renderTargetsEnabled) {
  17628. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17629. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  17630. var renderTarget = this.customRenderTargets[customIndex];
  17631. if (renderTarget._shouldRender()) {
  17632. this._renderId++;
  17633. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  17634. if (!this.activeCamera)
  17635. throw new Error("Active camera not set");
  17636. // Viewport
  17637. engine.setViewport(this.activeCamera.viewport);
  17638. // Camera
  17639. this.updateTransformMatrix();
  17640. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  17641. }
  17642. }
  17643. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17644. this._renderId++;
  17645. }
  17646. if (this.offscreenRenderTarget) {
  17647. engine.bindFramebuffer(this.offscreenRenderTarget._texture);
  17648. }
  17649. else {
  17650. // Restore back buffer
  17651. if (this.customRenderTargets.length > 0) {
  17652. engine.restoreDefaultFramebuffer();
  17653. }
  17654. }
  17655. this._renderTargetsDuration.endMonitoring();
  17656. this.activeCamera = currentActiveCamera;
  17657. // Procedural textures
  17658. if (this.proceduralTexturesEnabled) {
  17659. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17660. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  17661. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  17662. if (proceduralTexture._shouldRender()) {
  17663. proceduralTexture.render();
  17664. }
  17665. }
  17666. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17667. }
  17668. // Clear
  17669. if (this.autoClearDepthAndStencil || this.autoClear) {
  17670. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  17671. }
  17672. // Shadows
  17673. if (this.shadowsEnabled) {
  17674. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  17675. var light = this.lights[lightIndex];
  17676. var shadowGenerator = light.getShadowGenerator();
  17677. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  17678. var shadowMap = shadowGenerator.getShadowMap();
  17679. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  17680. this._renderTargets.push(shadowMap);
  17681. }
  17682. }
  17683. }
  17684. }
  17685. // Depth renderer
  17686. if (this._depthRenderer) {
  17687. this._renderTargets.push(this._depthRenderer.getDepthMap());
  17688. }
  17689. // Geometry renderer
  17690. if (this._geometryBufferRenderer) {
  17691. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  17692. }
  17693. // RenderPipeline
  17694. if (this._postProcessRenderPipelineManager) {
  17695. this._postProcessRenderPipelineManager.update();
  17696. }
  17697. // Multi-cameras?
  17698. if (this.activeCameras.length > 0) {
  17699. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  17700. if (cameraIndex > 0) {
  17701. this._engine.clear(null, false, true, true);
  17702. }
  17703. this._processSubCameras(this.activeCameras[cameraIndex]);
  17704. }
  17705. }
  17706. else {
  17707. if (!this.activeCamera) {
  17708. throw new Error("No camera defined");
  17709. }
  17710. this._processSubCameras(this.activeCamera);
  17711. }
  17712. // Intersection checks
  17713. this._checkIntersections();
  17714. // Update the audio listener attached to the camera
  17715. if (BABYLON.AudioEngine) {
  17716. this._updateAudioParameters();
  17717. }
  17718. // After render
  17719. if (this.afterRender) {
  17720. this.afterRender();
  17721. }
  17722. this.onAfterRenderObservable.notifyObservers(this);
  17723. // Cleaning
  17724. for (var index = 0; index < this._toBeDisposed.length; index++) {
  17725. this._toBeDisposed.data[index].dispose();
  17726. this._toBeDisposed[index] = null;
  17727. }
  17728. this._toBeDisposed.reset();
  17729. if (this.dumpNextRenderTargets) {
  17730. this.dumpNextRenderTargets = false;
  17731. }
  17732. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  17733. this._lastFrameDuration.endMonitoring();
  17734. this._totalMeshesCounter.addCount(this.meshes.length, true);
  17735. this._totalLightsCounter.addCount(this.lights.length, true);
  17736. this._totalMaterialsCounter.addCount(this.materials.length, true);
  17737. this._totalTexturesCounter.addCount(this.textures.length, true);
  17738. this._activeBones.addCount(0, true);
  17739. this._activeIndices.addCount(0, true);
  17740. this._activeParticles.addCount(0, true);
  17741. };
  17742. Scene.prototype._updateAudioParameters = function () {
  17743. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  17744. return;
  17745. }
  17746. var listeningCamera;
  17747. var audioEngine = BABYLON.Engine.audioEngine;
  17748. if (this.activeCameras.length > 0) {
  17749. listeningCamera = this.activeCameras[0];
  17750. }
  17751. else {
  17752. listeningCamera = this.activeCamera;
  17753. }
  17754. if (listeningCamera && audioEngine.canUseWebAudio) {
  17755. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  17756. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  17757. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  17758. cameraDirection.normalize();
  17759. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  17760. var i;
  17761. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17762. var sound = this.mainSoundTrack.soundCollection[i];
  17763. if (sound.useCustomAttenuation) {
  17764. sound.updateDistanceFromListener();
  17765. }
  17766. }
  17767. for (i = 0; i < this.soundTracks.length; i++) {
  17768. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17769. sound = this.soundTracks[i].soundCollection[j];
  17770. if (sound.useCustomAttenuation) {
  17771. sound.updateDistanceFromListener();
  17772. }
  17773. }
  17774. }
  17775. }
  17776. };
  17777. Object.defineProperty(Scene.prototype, "audioEnabled", {
  17778. // Audio
  17779. get: function () {
  17780. return this._audioEnabled;
  17781. },
  17782. set: function (value) {
  17783. this._audioEnabled = value;
  17784. if (BABYLON.AudioEngine) {
  17785. if (this._audioEnabled) {
  17786. this._enableAudio();
  17787. }
  17788. else {
  17789. this._disableAudio();
  17790. }
  17791. }
  17792. },
  17793. enumerable: true,
  17794. configurable: true
  17795. });
  17796. Scene.prototype._disableAudio = function () {
  17797. var i;
  17798. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17799. this.mainSoundTrack.soundCollection[i].pause();
  17800. }
  17801. for (i = 0; i < this.soundTracks.length; i++) {
  17802. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17803. this.soundTracks[i].soundCollection[j].pause();
  17804. }
  17805. }
  17806. };
  17807. Scene.prototype._enableAudio = function () {
  17808. var i;
  17809. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17810. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  17811. this.mainSoundTrack.soundCollection[i].play();
  17812. }
  17813. }
  17814. for (i = 0; i < this.soundTracks.length; i++) {
  17815. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17816. if (this.soundTracks[i].soundCollection[j].isPaused) {
  17817. this.soundTracks[i].soundCollection[j].play();
  17818. }
  17819. }
  17820. }
  17821. };
  17822. Object.defineProperty(Scene.prototype, "headphone", {
  17823. get: function () {
  17824. return this._headphone;
  17825. },
  17826. set: function (value) {
  17827. this._headphone = value;
  17828. if (BABYLON.AudioEngine) {
  17829. if (this._headphone) {
  17830. this._switchAudioModeForHeadphones();
  17831. }
  17832. else {
  17833. this._switchAudioModeForNormalSpeakers();
  17834. }
  17835. }
  17836. },
  17837. enumerable: true,
  17838. configurable: true
  17839. });
  17840. Scene.prototype._switchAudioModeForHeadphones = function () {
  17841. this.mainSoundTrack.switchPanningModelToHRTF();
  17842. for (var i = 0; i < this.soundTracks.length; i++) {
  17843. this.soundTracks[i].switchPanningModelToHRTF();
  17844. }
  17845. };
  17846. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  17847. this.mainSoundTrack.switchPanningModelToEqualPower();
  17848. for (var i = 0; i < this.soundTracks.length; i++) {
  17849. this.soundTracks[i].switchPanningModelToEqualPower();
  17850. }
  17851. };
  17852. Scene.prototype.enableDepthRenderer = function () {
  17853. if (this._depthRenderer) {
  17854. return this._depthRenderer;
  17855. }
  17856. this._depthRenderer = new BABYLON.DepthRenderer(this);
  17857. return this._depthRenderer;
  17858. };
  17859. Scene.prototype.disableDepthRenderer = function () {
  17860. if (!this._depthRenderer) {
  17861. return;
  17862. }
  17863. this._depthRenderer.dispose();
  17864. this._depthRenderer = null;
  17865. };
  17866. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  17867. if (ratio === void 0) { ratio = 1; }
  17868. if (this._geometryBufferRenderer) {
  17869. return this._geometryBufferRenderer;
  17870. }
  17871. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  17872. if (!this._geometryBufferRenderer.isSupported) {
  17873. this._geometryBufferRenderer = null;
  17874. }
  17875. return this._geometryBufferRenderer;
  17876. };
  17877. Scene.prototype.disableGeometryBufferRenderer = function () {
  17878. if (!this._geometryBufferRenderer) {
  17879. return;
  17880. }
  17881. this._geometryBufferRenderer.dispose();
  17882. this._geometryBufferRenderer = null;
  17883. };
  17884. Scene.prototype.freezeMaterials = function () {
  17885. for (var i = 0; i < this.materials.length; i++) {
  17886. this.materials[i].freeze();
  17887. }
  17888. };
  17889. Scene.prototype.unfreezeMaterials = function () {
  17890. for (var i = 0; i < this.materials.length; i++) {
  17891. this.materials[i].unfreeze();
  17892. }
  17893. };
  17894. Scene.prototype.dispose = function () {
  17895. this.beforeRender = null;
  17896. this.afterRender = null;
  17897. this.skeletons = [];
  17898. this.morphTargetManagers = [];
  17899. this.importedMeshesFiles = new Array();
  17900. if (this._depthRenderer) {
  17901. this._depthRenderer.dispose();
  17902. }
  17903. // Smart arrays
  17904. if (this.activeCamera) {
  17905. this.activeCamera._activeMeshes.dispose();
  17906. this.activeCamera = null;
  17907. }
  17908. this._activeMeshes.dispose();
  17909. this._renderingManager.dispose();
  17910. this._processedMaterials.dispose();
  17911. this._activeParticleSystems.dispose();
  17912. this._activeSkeletons.dispose();
  17913. this._softwareSkinnedMeshes.dispose();
  17914. if (this._boundingBoxRenderer) {
  17915. this._boundingBoxRenderer.dispose();
  17916. }
  17917. this._meshesForIntersections.dispose();
  17918. this._toBeDisposed.dispose();
  17919. // Debug layer
  17920. if (this._debugLayer) {
  17921. this._debugLayer.hide();
  17922. }
  17923. // Events
  17924. this.onDisposeObservable.notifyObservers(this);
  17925. this.onDisposeObservable.clear();
  17926. this.onBeforeRenderObservable.clear();
  17927. this.onAfterRenderObservable.clear();
  17928. this.detachControl();
  17929. // Release sounds & sounds tracks
  17930. if (BABYLON.AudioEngine) {
  17931. this.disposeSounds();
  17932. }
  17933. // Detach cameras
  17934. var canvas = this._engine.getRenderingCanvas();
  17935. var index;
  17936. for (index = 0; index < this.cameras.length; index++) {
  17937. this.cameras[index].detachControl(canvas);
  17938. }
  17939. // Release lights
  17940. while (this.lights.length) {
  17941. this.lights[0].dispose();
  17942. }
  17943. // Release meshes
  17944. while (this.meshes.length) {
  17945. this.meshes[0].dispose(true);
  17946. }
  17947. // Release cameras
  17948. while (this.cameras.length) {
  17949. this.cameras[0].dispose();
  17950. }
  17951. // Release materials
  17952. while (this.materials.length) {
  17953. this.materials[0].dispose();
  17954. }
  17955. // Release particles
  17956. while (this.particleSystems.length) {
  17957. this.particleSystems[0].dispose();
  17958. }
  17959. // Release sprites
  17960. while (this.spriteManagers.length) {
  17961. this.spriteManagers[0].dispose();
  17962. }
  17963. // Release layers
  17964. while (this.layers.length) {
  17965. this.layers[0].dispose();
  17966. }
  17967. while (this.highlightLayers.length) {
  17968. this.highlightLayers[0].dispose();
  17969. }
  17970. // Release textures
  17971. while (this.textures.length) {
  17972. this.textures[0].dispose();
  17973. }
  17974. // Release UBO
  17975. this._sceneUbo.dispose();
  17976. // Post-processes
  17977. this.postProcessManager.dispose();
  17978. // Physics
  17979. if (this._physicsEngine) {
  17980. this.disablePhysicsEngine();
  17981. }
  17982. // Remove from engine
  17983. index = this._engine.scenes.indexOf(this);
  17984. if (index > -1) {
  17985. this._engine.scenes.splice(index, 1);
  17986. }
  17987. this._engine.wipeCaches();
  17988. this._engine = null;
  17989. };
  17990. Object.defineProperty(Scene.prototype, "isDisposed", {
  17991. get: function () {
  17992. return !this._engine;
  17993. },
  17994. enumerable: true,
  17995. configurable: true
  17996. });
  17997. // Release sounds & sounds tracks
  17998. Scene.prototype.disposeSounds = function () {
  17999. this.mainSoundTrack.dispose();
  18000. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  18001. this.soundTracks[scIndex].dispose();
  18002. }
  18003. };
  18004. // Octrees
  18005. Scene.prototype.getWorldExtends = function () {
  18006. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18007. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18008. for (var index = 0; index < this.meshes.length; index++) {
  18009. var mesh = this.meshes[index];
  18010. mesh.computeWorldMatrix(true);
  18011. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  18012. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  18013. BABYLON.Tools.CheckExtends(minBox, min, max);
  18014. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18015. }
  18016. return {
  18017. min: min,
  18018. max: max
  18019. };
  18020. };
  18021. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  18022. if (maxCapacity === void 0) { maxCapacity = 64; }
  18023. if (maxDepth === void 0) { maxDepth = 2; }
  18024. if (!this._selectionOctree) {
  18025. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  18026. }
  18027. var worldExtends = this.getWorldExtends();
  18028. // Update octree
  18029. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  18030. return this._selectionOctree;
  18031. };
  18032. // Picking
  18033. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  18034. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  18035. var engine = this._engine;
  18036. if (!camera) {
  18037. if (!this.activeCamera)
  18038. throw new Error("Active camera not set");
  18039. camera = this.activeCamera;
  18040. }
  18041. var cameraViewport = camera.viewport;
  18042. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18043. // Moving coordinates to local viewport world
  18044. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18045. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18046. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  18047. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  18048. };
  18049. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  18050. if (!BABYLON.PickingInfo) {
  18051. return null;
  18052. }
  18053. var engine = this._engine;
  18054. if (!camera) {
  18055. if (!this.activeCamera)
  18056. throw new Error("Active camera not set");
  18057. camera = this.activeCamera;
  18058. }
  18059. var cameraViewport = camera.viewport;
  18060. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18061. var identity = BABYLON.Matrix.Identity();
  18062. // Moving coordinates to local viewport world
  18063. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18064. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18065. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  18066. };
  18067. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  18068. if (!BABYLON.PickingInfo) {
  18069. return null;
  18070. }
  18071. var pickingInfo = null;
  18072. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18073. var mesh = this.meshes[meshIndex];
  18074. if (predicate) {
  18075. if (!predicate(mesh)) {
  18076. continue;
  18077. }
  18078. }
  18079. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18080. continue;
  18081. }
  18082. var world = mesh.getWorldMatrix();
  18083. var ray = rayFunction(world);
  18084. var result = mesh.intersects(ray, fastCheck);
  18085. if (!result || !result.hit)
  18086. continue;
  18087. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18088. continue;
  18089. pickingInfo = result;
  18090. if (fastCheck) {
  18091. break;
  18092. }
  18093. }
  18094. return pickingInfo || new BABYLON.PickingInfo();
  18095. };
  18096. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  18097. if (!BABYLON.PickingInfo) {
  18098. return null;
  18099. }
  18100. var pickingInfos = new Array();
  18101. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18102. var mesh = this.meshes[meshIndex];
  18103. if (predicate) {
  18104. if (!predicate(mesh)) {
  18105. continue;
  18106. }
  18107. }
  18108. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18109. continue;
  18110. }
  18111. var world = mesh.getWorldMatrix();
  18112. var ray = rayFunction(world);
  18113. var result = mesh.intersects(ray, false);
  18114. if (!result || !result.hit)
  18115. continue;
  18116. pickingInfos.push(result);
  18117. }
  18118. return pickingInfos;
  18119. };
  18120. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  18121. if (!BABYLON.PickingInfo) {
  18122. return null;
  18123. }
  18124. var pickingInfo = null;
  18125. camera = camera || this.activeCamera;
  18126. if (this.spriteManagers.length > 0) {
  18127. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18128. var spriteManager = this.spriteManagers[spriteIndex];
  18129. if (!spriteManager.isPickable) {
  18130. continue;
  18131. }
  18132. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18133. if (!result || !result.hit)
  18134. continue;
  18135. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18136. continue;
  18137. pickingInfo = result;
  18138. if (fastCheck) {
  18139. break;
  18140. }
  18141. }
  18142. }
  18143. return pickingInfo || new BABYLON.PickingInfo();
  18144. };
  18145. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18146. /// <param name="x">X position on screen</param>
  18147. /// <param name="y">Y position on screen</param>
  18148. /// <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>
  18149. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18150. /// <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>
  18151. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  18152. var _this = this;
  18153. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  18154. };
  18155. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18156. /// <param name="x">X position on screen</param>
  18157. /// <param name="y">Y position on screen</param>
  18158. /// <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>
  18159. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18160. /// <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>
  18161. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  18162. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  18163. };
  18164. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  18165. var _this = this;
  18166. return this._internalPick(function (world) {
  18167. if (!_this._pickWithRayInverseMatrix) {
  18168. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18169. }
  18170. world.invertToRef(_this._pickWithRayInverseMatrix);
  18171. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18172. }, predicate, fastCheck);
  18173. };
  18174. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18175. /// <param name="x">X position on screen</param>
  18176. /// <param name="y">Y position on screen</param>
  18177. /// <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>
  18178. /// <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>
  18179. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  18180. var _this = this;
  18181. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  18182. };
  18183. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18184. /// <param name="ray">Ray to use</param>
  18185. /// <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>
  18186. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  18187. var _this = this;
  18188. return this._internalMultiPick(function (world) {
  18189. if (!_this._pickWithRayInverseMatrix) {
  18190. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18191. }
  18192. world.invertToRef(_this._pickWithRayInverseMatrix);
  18193. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18194. }, predicate);
  18195. };
  18196. Scene.prototype.setPointerOverMesh = function (mesh) {
  18197. if (this._pointerOverMesh === mesh) {
  18198. return;
  18199. }
  18200. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18201. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18202. }
  18203. this._pointerOverMesh = mesh;
  18204. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18205. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18206. }
  18207. };
  18208. Scene.prototype.getPointerOverMesh = function () {
  18209. return this._pointerOverMesh;
  18210. };
  18211. Scene.prototype.setPointerOverSprite = function (sprite) {
  18212. if (this._pointerOverSprite === sprite) {
  18213. return;
  18214. }
  18215. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18216. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18217. }
  18218. this._pointerOverSprite = sprite;
  18219. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18220. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18221. }
  18222. };
  18223. Scene.prototype.getPointerOverSprite = function () {
  18224. return this._pointerOverSprite;
  18225. };
  18226. // Physics
  18227. Scene.prototype.getPhysicsEngine = function () {
  18228. return this._physicsEngine;
  18229. };
  18230. /**
  18231. * Enables physics to the current scene
  18232. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  18233. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  18234. * @return {boolean} was the physics engine initialized
  18235. */
  18236. Scene.prototype.enablePhysics = function (gravity, plugin) {
  18237. if (this._physicsEngine) {
  18238. return true;
  18239. }
  18240. try {
  18241. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  18242. return true;
  18243. }
  18244. catch (e) {
  18245. BABYLON.Tools.Error(e.message);
  18246. return false;
  18247. }
  18248. };
  18249. Scene.prototype.disablePhysicsEngine = function () {
  18250. if (!this._physicsEngine) {
  18251. return;
  18252. }
  18253. this._physicsEngine.dispose();
  18254. this._physicsEngine = undefined;
  18255. };
  18256. Scene.prototype.isPhysicsEnabled = function () {
  18257. return this._physicsEngine !== undefined;
  18258. };
  18259. Scene.prototype.deleteCompoundImpostor = function (compound) {
  18260. var mesh = compound.parts[0].mesh;
  18261. mesh.physicsImpostor.dispose();
  18262. mesh.physicsImpostor = null;
  18263. };
  18264. // Misc.
  18265. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  18266. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  18267. // Light
  18268. if (this.lights.length === 0) {
  18269. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  18270. }
  18271. // Camera
  18272. if (!this.activeCamera) {
  18273. var worldExtends = this.getWorldExtends();
  18274. var worldSize = worldExtends.max.subtract(worldExtends.min);
  18275. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  18276. var camera;
  18277. var radius = worldSize.length() * 1.5;
  18278. if (createArcRotateCamera) {
  18279. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", 4.712, 1.571, radius, worldCenter, this);
  18280. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  18281. arcRotateCamera.wheelPrecision = 100 / radius;
  18282. camera = arcRotateCamera;
  18283. }
  18284. else {
  18285. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, this.useRightHandedSystem ? -radius : radius), this);
  18286. freeCamera.setTarget(worldCenter);
  18287. camera = freeCamera;
  18288. }
  18289. camera.minZ = radius * 0.01;
  18290. camera.maxZ = radius * 100;
  18291. camera.speed = radius * 0.2;
  18292. this.activeCamera = camera;
  18293. }
  18294. };
  18295. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr) {
  18296. if (pbr === void 0) { pbr = false; }
  18297. if (environmentTexture) {
  18298. this.environmentTexture = environmentTexture;
  18299. }
  18300. if (!this.environmentTexture) {
  18301. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  18302. return;
  18303. }
  18304. if (!this.environmentTexture) {
  18305. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  18306. return;
  18307. }
  18308. // Skybox
  18309. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", 1000.0, this);
  18310. if (pbr) {
  18311. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  18312. hdrSkyboxMaterial.backFaceCulling = false;
  18313. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  18314. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  18315. hdrSkyboxMaterial.microSurface = 1.0;
  18316. hdrSkyboxMaterial.disableLighting = true;
  18317. hdrSkybox.infiniteDistance = true;
  18318. hdrSkybox.material = hdrSkyboxMaterial;
  18319. }
  18320. else {
  18321. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  18322. skyboxMaterial.backFaceCulling = false;
  18323. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  18324. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  18325. skyboxMaterial.diffuseColor = new BABYLON.Color3(0, 0, 0);
  18326. skyboxMaterial.specularColor = new BABYLON.Color3(0, 0, 0);
  18327. skyboxMaterial.disableLighting = true;
  18328. hdrSkybox.infiniteDistance = true;
  18329. hdrSkybox.material = skyboxMaterial;
  18330. }
  18331. return hdrSkybox;
  18332. };
  18333. // Tags
  18334. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  18335. if (tagsQuery === undefined) {
  18336. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  18337. return list;
  18338. }
  18339. var listByTags = [];
  18340. forEach = forEach || (function (item) { return; });
  18341. for (var i in list) {
  18342. var item = list[i];
  18343. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  18344. listByTags.push(item);
  18345. forEach(item);
  18346. }
  18347. }
  18348. return listByTags;
  18349. };
  18350. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  18351. return this._getByTags(this.meshes, tagsQuery, forEach);
  18352. };
  18353. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  18354. return this._getByTags(this.cameras, tagsQuery, forEach);
  18355. };
  18356. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  18357. return this._getByTags(this.lights, tagsQuery, forEach);
  18358. };
  18359. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  18360. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  18361. };
  18362. /**
  18363. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18364. * This allowed control for front to back rendering or reversly depending of the special needs.
  18365. *
  18366. * @param renderingGroupId The rendering group id corresponding to its index
  18367. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18368. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18369. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18370. */
  18371. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18372. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18373. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18374. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18375. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  18376. };
  18377. /**
  18378. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18379. *
  18380. * @param renderingGroupId The rendering group id corresponding to its index
  18381. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18382. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18383. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18384. */
  18385. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18386. if (depth === void 0) { depth = true; }
  18387. if (stencil === void 0) { stencil = true; }
  18388. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  18389. };
  18390. /**
  18391. * Will flag all materials as dirty to trigger new shader compilation
  18392. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  18393. */
  18394. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  18395. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  18396. var material = _a[_i];
  18397. if (predicate && !predicate(material)) {
  18398. continue;
  18399. }
  18400. material.markAsDirty(flag);
  18401. }
  18402. };
  18403. return Scene;
  18404. }());
  18405. // Statics
  18406. Scene._FOGMODE_NONE = 0;
  18407. Scene._FOGMODE_EXP = 1;
  18408. Scene._FOGMODE_EXP2 = 2;
  18409. Scene._FOGMODE_LINEAR = 3;
  18410. Scene.MinDeltaTime = 1.0;
  18411. Scene.MaxDeltaTime = 1000.0;
  18412. Scene.DragMovementThreshold = 10; // in pixels
  18413. Scene.LongPressDelay = 500; // in milliseconds
  18414. Scene.DoubleClickDelay = 300; // in milliseconds
  18415. Scene.ExclusiveDoubleClickMode = false; // If you need to check double click without raising a single click at first click, enable this flag
  18416. BABYLON.Scene = Scene;
  18417. })(BABYLON || (BABYLON = {}));
  18418. //# sourceMappingURL=babylon.scene.js.map
  18419. var BABYLON;
  18420. (function (BABYLON) {
  18421. var Buffer = (function () {
  18422. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  18423. if (engine instanceof BABYLON.Mesh) {
  18424. this._engine = engine.getScene().getEngine();
  18425. }
  18426. else {
  18427. this._engine = engine;
  18428. }
  18429. this._updatable = updatable;
  18430. this._data = data;
  18431. this._strideSize = stride;
  18432. if (!postponeInternalCreation) {
  18433. this.create();
  18434. }
  18435. this._instanced = instanced;
  18436. }
  18437. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  18438. // a lot of these parameters are ignored as they are overriden by the buffer
  18439. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  18440. };
  18441. // Properties
  18442. Buffer.prototype.isUpdatable = function () {
  18443. return this._updatable;
  18444. };
  18445. Buffer.prototype.getData = function () {
  18446. return this._data;
  18447. };
  18448. Buffer.prototype.getBuffer = function () {
  18449. return this._buffer;
  18450. };
  18451. Buffer.prototype.getStrideSize = function () {
  18452. return this._strideSize;
  18453. };
  18454. Buffer.prototype.getIsInstanced = function () {
  18455. return this._instanced;
  18456. };
  18457. // Methods
  18458. Buffer.prototype.create = function (data) {
  18459. if (!data && this._buffer) {
  18460. return; // nothing to do
  18461. }
  18462. data = data || this._data;
  18463. if (!this._buffer) {
  18464. if (this._updatable) {
  18465. this._buffer = this._engine.createDynamicVertexBuffer(data);
  18466. this._data = data;
  18467. }
  18468. else {
  18469. this._buffer = this._engine.createVertexBuffer(data);
  18470. }
  18471. }
  18472. else if (this._updatable) {
  18473. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  18474. this._data = data;
  18475. }
  18476. };
  18477. Buffer.prototype.update = function (data) {
  18478. this.create(data);
  18479. };
  18480. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  18481. if (!this._buffer) {
  18482. return;
  18483. }
  18484. if (this._updatable) {
  18485. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  18486. this._data = null;
  18487. }
  18488. };
  18489. Buffer.prototype.dispose = function () {
  18490. if (!this._buffer) {
  18491. return;
  18492. }
  18493. if (this._engine._releaseBuffer(this._buffer)) {
  18494. this._buffer = null;
  18495. }
  18496. };
  18497. return Buffer;
  18498. }());
  18499. BABYLON.Buffer = Buffer;
  18500. })(BABYLON || (BABYLON = {}));
  18501. //# sourceMappingURL=babylon.buffer.js.map
  18502. var BABYLON;
  18503. (function (BABYLON) {
  18504. var VertexBuffer = (function () {
  18505. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  18506. if (!stride) {
  18507. // Deduce stride from kind
  18508. switch (kind) {
  18509. case VertexBuffer.PositionKind:
  18510. stride = 3;
  18511. break;
  18512. case VertexBuffer.NormalKind:
  18513. stride = 3;
  18514. break;
  18515. case VertexBuffer.UVKind:
  18516. case VertexBuffer.UV2Kind:
  18517. case VertexBuffer.UV3Kind:
  18518. case VertexBuffer.UV4Kind:
  18519. case VertexBuffer.UV5Kind:
  18520. case VertexBuffer.UV6Kind:
  18521. stride = 2;
  18522. break;
  18523. case VertexBuffer.TangentKind:
  18524. case VertexBuffer.ColorKind:
  18525. stride = 4;
  18526. break;
  18527. case VertexBuffer.MatricesIndicesKind:
  18528. case VertexBuffer.MatricesIndicesExtraKind:
  18529. stride = 4;
  18530. break;
  18531. case VertexBuffer.MatricesWeightsKind:
  18532. case VertexBuffer.MatricesWeightsExtraKind:
  18533. stride = 4;
  18534. break;
  18535. }
  18536. }
  18537. if (data instanceof BABYLON.Buffer) {
  18538. if (!stride) {
  18539. stride = data.getStrideSize();
  18540. }
  18541. this._buffer = data;
  18542. this._ownsBuffer = false;
  18543. }
  18544. else {
  18545. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  18546. this._ownsBuffer = true;
  18547. }
  18548. this._stride = stride;
  18549. this._offset = offset ? offset : 0;
  18550. this._size = size ? size : stride;
  18551. this._kind = kind;
  18552. }
  18553. /**
  18554. * Returns the kind of the VertexBuffer (string).
  18555. */
  18556. VertexBuffer.prototype.getKind = function () {
  18557. return this._kind;
  18558. };
  18559. // Properties
  18560. /**
  18561. * Boolean : is the VertexBuffer updatable ?
  18562. */
  18563. VertexBuffer.prototype.isUpdatable = function () {
  18564. return this._buffer.isUpdatable();
  18565. };
  18566. /**
  18567. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  18568. */
  18569. VertexBuffer.prototype.getData = function () {
  18570. return this._buffer.getData();
  18571. };
  18572. /**
  18573. * Returns the WebGLBuffer associated to the VertexBuffer.
  18574. */
  18575. VertexBuffer.prototype.getBuffer = function () {
  18576. return this._buffer.getBuffer();
  18577. };
  18578. /**
  18579. * Returns the stride of the VertexBuffer (integer).
  18580. */
  18581. VertexBuffer.prototype.getStrideSize = function () {
  18582. return this._stride;
  18583. };
  18584. /**
  18585. * Returns the offset (integer).
  18586. */
  18587. VertexBuffer.prototype.getOffset = function () {
  18588. return this._offset;
  18589. };
  18590. /**
  18591. * Returns the VertexBuffer total size (integer).
  18592. */
  18593. VertexBuffer.prototype.getSize = function () {
  18594. return this._size;
  18595. };
  18596. /**
  18597. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  18598. */
  18599. VertexBuffer.prototype.getIsInstanced = function () {
  18600. return this._buffer.getIsInstanced();
  18601. };
  18602. // Methods
  18603. /**
  18604. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  18605. * Returns the created WebGLBuffer.
  18606. */
  18607. VertexBuffer.prototype.create = function (data) {
  18608. return this._buffer.create(data);
  18609. };
  18610. /**
  18611. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  18612. * Returns the updated WebGLBuffer.
  18613. */
  18614. VertexBuffer.prototype.update = function (data) {
  18615. return this._buffer.update(data);
  18616. };
  18617. /**
  18618. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  18619. * Returns the directly updated WebGLBuffer.
  18620. */
  18621. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  18622. return this._buffer.updateDirectly(data, offset);
  18623. };
  18624. /**
  18625. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  18626. */
  18627. VertexBuffer.prototype.dispose = function () {
  18628. if (this._ownsBuffer) {
  18629. this._buffer.dispose();
  18630. }
  18631. };
  18632. Object.defineProperty(VertexBuffer, "PositionKind", {
  18633. get: function () {
  18634. return VertexBuffer._PositionKind;
  18635. },
  18636. enumerable: true,
  18637. configurable: true
  18638. });
  18639. Object.defineProperty(VertexBuffer, "NormalKind", {
  18640. get: function () {
  18641. return VertexBuffer._NormalKind;
  18642. },
  18643. enumerable: true,
  18644. configurable: true
  18645. });
  18646. Object.defineProperty(VertexBuffer, "TangentKind", {
  18647. get: function () {
  18648. return VertexBuffer._TangentKind;
  18649. },
  18650. enumerable: true,
  18651. configurable: true
  18652. });
  18653. Object.defineProperty(VertexBuffer, "UVKind", {
  18654. get: function () {
  18655. return VertexBuffer._UVKind;
  18656. },
  18657. enumerable: true,
  18658. configurable: true
  18659. });
  18660. Object.defineProperty(VertexBuffer, "UV2Kind", {
  18661. get: function () {
  18662. return VertexBuffer._UV2Kind;
  18663. },
  18664. enumerable: true,
  18665. configurable: true
  18666. });
  18667. Object.defineProperty(VertexBuffer, "UV3Kind", {
  18668. get: function () {
  18669. return VertexBuffer._UV3Kind;
  18670. },
  18671. enumerable: true,
  18672. configurable: true
  18673. });
  18674. Object.defineProperty(VertexBuffer, "UV4Kind", {
  18675. get: function () {
  18676. return VertexBuffer._UV4Kind;
  18677. },
  18678. enumerable: true,
  18679. configurable: true
  18680. });
  18681. Object.defineProperty(VertexBuffer, "UV5Kind", {
  18682. get: function () {
  18683. return VertexBuffer._UV5Kind;
  18684. },
  18685. enumerable: true,
  18686. configurable: true
  18687. });
  18688. Object.defineProperty(VertexBuffer, "UV6Kind", {
  18689. get: function () {
  18690. return VertexBuffer._UV6Kind;
  18691. },
  18692. enumerable: true,
  18693. configurable: true
  18694. });
  18695. Object.defineProperty(VertexBuffer, "ColorKind", {
  18696. get: function () {
  18697. return VertexBuffer._ColorKind;
  18698. },
  18699. enumerable: true,
  18700. configurable: true
  18701. });
  18702. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  18703. get: function () {
  18704. return VertexBuffer._MatricesIndicesKind;
  18705. },
  18706. enumerable: true,
  18707. configurable: true
  18708. });
  18709. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  18710. get: function () {
  18711. return VertexBuffer._MatricesWeightsKind;
  18712. },
  18713. enumerable: true,
  18714. configurable: true
  18715. });
  18716. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  18717. get: function () {
  18718. return VertexBuffer._MatricesIndicesExtraKind;
  18719. },
  18720. enumerable: true,
  18721. configurable: true
  18722. });
  18723. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  18724. get: function () {
  18725. return VertexBuffer._MatricesWeightsExtraKind;
  18726. },
  18727. enumerable: true,
  18728. configurable: true
  18729. });
  18730. return VertexBuffer;
  18731. }());
  18732. // Enums
  18733. VertexBuffer._PositionKind = "position";
  18734. VertexBuffer._NormalKind = "normal";
  18735. VertexBuffer._TangentKind = "tangent";
  18736. VertexBuffer._UVKind = "uv";
  18737. VertexBuffer._UV2Kind = "uv2";
  18738. VertexBuffer._UV3Kind = "uv3";
  18739. VertexBuffer._UV4Kind = "uv4";
  18740. VertexBuffer._UV5Kind = "uv5";
  18741. VertexBuffer._UV6Kind = "uv6";
  18742. VertexBuffer._ColorKind = "color";
  18743. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  18744. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  18745. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  18746. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  18747. BABYLON.VertexBuffer = VertexBuffer;
  18748. })(BABYLON || (BABYLON = {}));
  18749. //# sourceMappingURL=babylon.vertexBuffer.js.map
  18750. var BABYLON;
  18751. (function (BABYLON) {
  18752. var BaseTexture = (function () {
  18753. function BaseTexture(scene) {
  18754. this._hasAlpha = false;
  18755. this.getAlphaFromRGB = false;
  18756. this.level = 1;
  18757. this.coordinatesIndex = 0;
  18758. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  18759. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  18760. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  18761. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  18762. this.isCube = false;
  18763. this.isRenderTarget = false;
  18764. this.animations = new Array();
  18765. /**
  18766. * An event triggered when the texture is disposed.
  18767. * @type {BABYLON.Observable}
  18768. */
  18769. this.onDisposeObservable = new BABYLON.Observable();
  18770. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18771. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  18772. this._scene.textures.push(this);
  18773. this._uid = null;
  18774. }
  18775. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  18776. get: function () {
  18777. return this._hasAlpha;
  18778. },
  18779. set: function (value) {
  18780. if (this._hasAlpha === value) {
  18781. return;
  18782. }
  18783. this._hasAlpha = value;
  18784. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18785. },
  18786. enumerable: true,
  18787. configurable: true
  18788. });
  18789. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  18790. get: function () {
  18791. return this._coordinatesMode;
  18792. },
  18793. set: function (value) {
  18794. if (this._coordinatesMode === value) {
  18795. return;
  18796. }
  18797. this._coordinatesMode = value;
  18798. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18799. },
  18800. enumerable: true,
  18801. configurable: true
  18802. });
  18803. Object.defineProperty(BaseTexture.prototype, "uid", {
  18804. get: function () {
  18805. if (!this._uid) {
  18806. this._uid = BABYLON.Tools.RandomId();
  18807. }
  18808. return this._uid;
  18809. },
  18810. enumerable: true,
  18811. configurable: true
  18812. });
  18813. BaseTexture.prototype.toString = function () {
  18814. return this.name;
  18815. };
  18816. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  18817. set: function (callback) {
  18818. if (this._onDisposeObserver) {
  18819. this.onDisposeObservable.remove(this._onDisposeObserver);
  18820. }
  18821. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18822. },
  18823. enumerable: true,
  18824. configurable: true
  18825. });
  18826. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  18827. get: function () {
  18828. return true;
  18829. },
  18830. enumerable: true,
  18831. configurable: true
  18832. });
  18833. BaseTexture.prototype.getScene = function () {
  18834. return this._scene;
  18835. };
  18836. BaseTexture.prototype.getTextureMatrix = function () {
  18837. return null;
  18838. };
  18839. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  18840. return null;
  18841. };
  18842. BaseTexture.prototype.getInternalTexture = function () {
  18843. return this._texture;
  18844. };
  18845. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  18846. return !this.isBlocking || this.isReady();
  18847. };
  18848. BaseTexture.prototype.isReady = function () {
  18849. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18850. this.delayLoad();
  18851. return false;
  18852. }
  18853. if (this._texture) {
  18854. return this._texture.isReady;
  18855. }
  18856. return false;
  18857. };
  18858. BaseTexture.prototype.getSize = function () {
  18859. if (this._texture._width) {
  18860. return new BABYLON.Size(this._texture._width, this._texture._height);
  18861. }
  18862. if (this._texture._size) {
  18863. return new BABYLON.Size(this._texture._size, this._texture._size);
  18864. }
  18865. return BABYLON.Size.Zero();
  18866. };
  18867. BaseTexture.prototype.getBaseSize = function () {
  18868. if (!this.isReady() || !this._texture)
  18869. return BABYLON.Size.Zero();
  18870. if (this._texture._size) {
  18871. return new BABYLON.Size(this._texture._size, this._texture._size);
  18872. }
  18873. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  18874. };
  18875. BaseTexture.prototype.scale = function (ratio) {
  18876. };
  18877. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  18878. get: function () {
  18879. return false;
  18880. },
  18881. enumerable: true,
  18882. configurable: true
  18883. });
  18884. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  18885. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  18886. for (var index = 0; index < texturesCache.length; index++) {
  18887. var texturesCacheEntry = texturesCache[index];
  18888. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  18889. texturesCache.splice(index, 1);
  18890. return;
  18891. }
  18892. }
  18893. };
  18894. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  18895. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  18896. for (var index = 0; index < texturesCache.length; index++) {
  18897. var texturesCacheEntry = texturesCache[index];
  18898. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  18899. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  18900. texturesCacheEntry.references++;
  18901. return texturesCacheEntry;
  18902. }
  18903. }
  18904. }
  18905. return null;
  18906. };
  18907. BaseTexture.prototype.delayLoad = function () {
  18908. };
  18909. BaseTexture.prototype.clone = function () {
  18910. return null;
  18911. };
  18912. BaseTexture.prototype.releaseInternalTexture = function () {
  18913. if (this._texture) {
  18914. this._scene.getEngine().releaseInternalTexture(this._texture);
  18915. delete this._texture;
  18916. }
  18917. };
  18918. BaseTexture.prototype.dispose = function () {
  18919. // Animations
  18920. this.getScene().stopAnimation(this);
  18921. // Remove from scene
  18922. this._scene._removePendingData(this);
  18923. var index = this._scene.textures.indexOf(this);
  18924. if (index >= 0) {
  18925. this._scene.textures.splice(index, 1);
  18926. }
  18927. if (this._texture === undefined) {
  18928. return;
  18929. }
  18930. // Release
  18931. this.releaseInternalTexture();
  18932. // Callback
  18933. this.onDisposeObservable.notifyObservers(this);
  18934. this.onDisposeObservable.clear();
  18935. };
  18936. BaseTexture.prototype.serialize = function () {
  18937. if (!this.name) {
  18938. return null;
  18939. }
  18940. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18941. // Animations
  18942. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18943. return serializationObject;
  18944. };
  18945. return BaseTexture;
  18946. }());
  18947. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  18948. __decorate([
  18949. BABYLON.serialize()
  18950. ], BaseTexture.prototype, "name", void 0);
  18951. __decorate([
  18952. BABYLON.serialize("hasAlpha")
  18953. ], BaseTexture.prototype, "_hasAlpha", void 0);
  18954. __decorate([
  18955. BABYLON.serialize()
  18956. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  18957. __decorate([
  18958. BABYLON.serialize()
  18959. ], BaseTexture.prototype, "level", void 0);
  18960. __decorate([
  18961. BABYLON.serialize()
  18962. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  18963. __decorate([
  18964. BABYLON.serialize("coordinatesMode")
  18965. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  18966. __decorate([
  18967. BABYLON.serialize()
  18968. ], BaseTexture.prototype, "wrapU", void 0);
  18969. __decorate([
  18970. BABYLON.serialize()
  18971. ], BaseTexture.prototype, "wrapV", void 0);
  18972. __decorate([
  18973. BABYLON.serialize()
  18974. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  18975. __decorate([
  18976. BABYLON.serialize()
  18977. ], BaseTexture.prototype, "isCube", void 0);
  18978. __decorate([
  18979. BABYLON.serialize()
  18980. ], BaseTexture.prototype, "isRenderTarget", void 0);
  18981. BABYLON.BaseTexture = BaseTexture;
  18982. })(BABYLON || (BABYLON = {}));
  18983. //# sourceMappingURL=babylon.baseTexture.js.map
  18984. var BABYLON;
  18985. (function (BABYLON) {
  18986. var Texture = (function (_super) {
  18987. __extends(Texture, _super);
  18988. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  18989. if (noMipmap === void 0) { noMipmap = false; }
  18990. if (invertY === void 0) { invertY = true; }
  18991. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  18992. if (onLoad === void 0) { onLoad = null; }
  18993. if (onError === void 0) { onError = null; }
  18994. if (buffer === void 0) { buffer = null; }
  18995. if (deleteBuffer === void 0) { deleteBuffer = false; }
  18996. var _this = _super.call(this, scene) || this;
  18997. _this.uOffset = 0;
  18998. _this.vOffset = 0;
  18999. _this.uScale = 1.0;
  19000. _this.vScale = 1.0;
  19001. _this.uAng = 0;
  19002. _this.vAng = 0;
  19003. _this.wAng = 0;
  19004. _this._isBlocking = true;
  19005. _this.name = url;
  19006. _this.url = url;
  19007. _this._noMipmap = noMipmap;
  19008. _this._invertY = invertY;
  19009. _this._samplingMode = samplingMode;
  19010. _this._buffer = buffer;
  19011. _this._deleteBuffer = deleteBuffer;
  19012. _this._format = format;
  19013. scene = _this.getScene();
  19014. if (!url) {
  19015. return _this;
  19016. }
  19017. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  19018. var load = function () {
  19019. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  19020. _this.onLoadObservable.notifyObservers(true);
  19021. }
  19022. if (onLoad) {
  19023. onLoad();
  19024. }
  19025. if (!_this.isBlocking) {
  19026. scene.resetCachedMaterial();
  19027. }
  19028. };
  19029. if (!_this._texture) {
  19030. if (!scene.useDelayedTextureLoading) {
  19031. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  19032. if (deleteBuffer) {
  19033. delete _this._buffer;
  19034. }
  19035. }
  19036. else {
  19037. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19038. _this._delayedOnLoad = load;
  19039. _this._delayedOnError = onError;
  19040. }
  19041. }
  19042. else {
  19043. if (_this._texture.isReady) {
  19044. BABYLON.Tools.SetImmediate(function () { return load(); });
  19045. }
  19046. else {
  19047. _this._texture.onLoadedCallbacks.push(load);
  19048. }
  19049. }
  19050. return _this;
  19051. }
  19052. Object.defineProperty(Texture.prototype, "noMipmap", {
  19053. get: function () {
  19054. return this._noMipmap;
  19055. },
  19056. enumerable: true,
  19057. configurable: true
  19058. });
  19059. Object.defineProperty(Texture.prototype, "isBlocking", {
  19060. get: function () {
  19061. return this._isBlocking;
  19062. },
  19063. set: function (value) {
  19064. this._isBlocking = value;
  19065. },
  19066. enumerable: true,
  19067. configurable: true
  19068. });
  19069. Texture.prototype.delayLoad = function () {
  19070. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19071. return;
  19072. }
  19073. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19074. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  19075. if (!this._texture) {
  19076. 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);
  19077. if (this._deleteBuffer) {
  19078. delete this._buffer;
  19079. }
  19080. }
  19081. };
  19082. Texture.prototype.updateSamplingMode = function (samplingMode) {
  19083. if (!this._texture) {
  19084. return;
  19085. }
  19086. this._samplingMode = samplingMode;
  19087. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  19088. };
  19089. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  19090. x *= this.uScale;
  19091. y *= this.vScale;
  19092. x -= 0.5 * this.uScale;
  19093. y -= 0.5 * this.vScale;
  19094. z -= 0.5;
  19095. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  19096. t.x += 0.5 * this.uScale + this.uOffset;
  19097. t.y += 0.5 * this.vScale + this.vOffset;
  19098. t.z += 0.5;
  19099. };
  19100. Texture.prototype.getTextureMatrix = function () {
  19101. if (this.uOffset === this._cachedUOffset &&
  19102. this.vOffset === this._cachedVOffset &&
  19103. this.uScale === this._cachedUScale &&
  19104. this.vScale === this._cachedVScale &&
  19105. this.uAng === this._cachedUAng &&
  19106. this.vAng === this._cachedVAng &&
  19107. this.wAng === this._cachedWAng) {
  19108. return this._cachedTextureMatrix;
  19109. }
  19110. this._cachedUOffset = this.uOffset;
  19111. this._cachedVOffset = this.vOffset;
  19112. this._cachedUScale = this.uScale;
  19113. this._cachedVScale = this.vScale;
  19114. this._cachedUAng = this.uAng;
  19115. this._cachedVAng = this.vAng;
  19116. this._cachedWAng = this.wAng;
  19117. if (!this._cachedTextureMatrix) {
  19118. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19119. this._rowGenerationMatrix = new BABYLON.Matrix();
  19120. this._t0 = BABYLON.Vector3.Zero();
  19121. this._t1 = BABYLON.Vector3.Zero();
  19122. this._t2 = BABYLON.Vector3.Zero();
  19123. }
  19124. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  19125. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  19126. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  19127. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  19128. this._t1.subtractInPlace(this._t0);
  19129. this._t2.subtractInPlace(this._t0);
  19130. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19131. this._cachedTextureMatrix.m[0] = this._t1.x;
  19132. this._cachedTextureMatrix.m[1] = this._t1.y;
  19133. this._cachedTextureMatrix.m[2] = this._t1.z;
  19134. this._cachedTextureMatrix.m[4] = this._t2.x;
  19135. this._cachedTextureMatrix.m[5] = this._t2.y;
  19136. this._cachedTextureMatrix.m[6] = this._t2.z;
  19137. this._cachedTextureMatrix.m[8] = this._t0.x;
  19138. this._cachedTextureMatrix.m[9] = this._t0.y;
  19139. this._cachedTextureMatrix.m[10] = this._t0.z;
  19140. return this._cachedTextureMatrix;
  19141. };
  19142. Texture.prototype.getReflectionTextureMatrix = function () {
  19143. if (this.uOffset === this._cachedUOffset &&
  19144. this.vOffset === this._cachedVOffset &&
  19145. this.uScale === this._cachedUScale &&
  19146. this.vScale === this._cachedVScale &&
  19147. this.coordinatesMode === this._cachedCoordinatesMode) {
  19148. return this._cachedTextureMatrix;
  19149. }
  19150. if (!this._cachedTextureMatrix) {
  19151. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  19152. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  19153. }
  19154. this._cachedCoordinatesMode = this.coordinatesMode;
  19155. switch (this.coordinatesMode) {
  19156. case Texture.PLANAR_MODE:
  19157. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19158. this._cachedTextureMatrix[0] = this.uScale;
  19159. this._cachedTextureMatrix[5] = this.vScale;
  19160. this._cachedTextureMatrix[12] = this.uOffset;
  19161. this._cachedTextureMatrix[13] = this.vOffset;
  19162. break;
  19163. case Texture.PROJECTION_MODE:
  19164. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  19165. this._projectionModeMatrix.m[0] = 0.5;
  19166. this._projectionModeMatrix.m[5] = -0.5;
  19167. this._projectionModeMatrix.m[10] = 0.0;
  19168. this._projectionModeMatrix.m[12] = 0.5;
  19169. this._projectionModeMatrix.m[13] = 0.5;
  19170. this._projectionModeMatrix.m[14] = 1.0;
  19171. this._projectionModeMatrix.m[15] = 1.0;
  19172. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  19173. break;
  19174. default:
  19175. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  19176. break;
  19177. }
  19178. return this._cachedTextureMatrix;
  19179. };
  19180. Texture.prototype.clone = function () {
  19181. var _this = this;
  19182. return BABYLON.SerializationHelper.Clone(function () {
  19183. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  19184. }, this);
  19185. };
  19186. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  19187. get: function () {
  19188. if (!this._onLoadObservarble) {
  19189. this._onLoadObservarble = new BABYLON.Observable();
  19190. }
  19191. return this._onLoadObservarble;
  19192. },
  19193. enumerable: true,
  19194. configurable: true
  19195. });
  19196. // Statics
  19197. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  19198. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19199. if (onLoad === void 0) { onLoad = null; }
  19200. if (onError === void 0) { onError = null; }
  19201. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  19202. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  19203. };
  19204. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  19205. if (parsedTexture.customType) {
  19206. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  19207. // Update Sampling Mode
  19208. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  19209. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  19210. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  19211. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  19212. }
  19213. }
  19214. return parsedCustomTexture;
  19215. }
  19216. if (parsedTexture.isCube) {
  19217. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  19218. }
  19219. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19220. return null;
  19221. }
  19222. var texture = BABYLON.SerializationHelper.Parse(function () {
  19223. if (parsedTexture.mirrorPlane) {
  19224. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19225. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  19226. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19227. return mirrorTexture;
  19228. }
  19229. else if (parsedTexture.isRenderTarget) {
  19230. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19231. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  19232. return renderTargetTexture;
  19233. }
  19234. else {
  19235. var texture;
  19236. if (parsedTexture.base64String) {
  19237. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19238. }
  19239. else {
  19240. texture = new Texture(rootUrl + parsedTexture.name, scene);
  19241. }
  19242. return texture;
  19243. }
  19244. }, parsedTexture, scene);
  19245. // Update Sampling Mode
  19246. if (parsedTexture.samplingMode) {
  19247. var sampling = parsedTexture.samplingMode;
  19248. if (texture._samplingMode !== sampling) {
  19249. texture.updateSamplingMode(sampling);
  19250. }
  19251. }
  19252. // Animations
  19253. if (parsedTexture.animations) {
  19254. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19255. var parsedAnimation = parsedTexture.animations[animationIndex];
  19256. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19257. }
  19258. }
  19259. return texture;
  19260. };
  19261. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  19262. if (deleteBuffer === void 0) { deleteBuffer = false; }
  19263. if (noMipmap === void 0) { noMipmap = false; }
  19264. if (invertY === void 0) { invertY = true; }
  19265. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  19266. if (onLoad === void 0) { onLoad = null; }
  19267. if (onError === void 0) { onError = null; }
  19268. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  19269. if (name.substr(0, 5) !== "data:") {
  19270. name = "data:" + name;
  19271. }
  19272. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  19273. };
  19274. return Texture;
  19275. }(BABYLON.BaseTexture));
  19276. // Constants
  19277. Texture.NEAREST_SAMPLINGMODE = 1;
  19278. Texture.BILINEAR_SAMPLINGMODE = 2;
  19279. Texture.TRILINEAR_SAMPLINGMODE = 3;
  19280. Texture.EXPLICIT_MODE = 0;
  19281. Texture.SPHERICAL_MODE = 1;
  19282. Texture.PLANAR_MODE = 2;
  19283. Texture.CUBIC_MODE = 3;
  19284. Texture.PROJECTION_MODE = 4;
  19285. Texture.SKYBOX_MODE = 5;
  19286. Texture.INVCUBIC_MODE = 6;
  19287. Texture.EQUIRECTANGULAR_MODE = 7;
  19288. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  19289. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  19290. Texture.CLAMP_ADDRESSMODE = 0;
  19291. Texture.WRAP_ADDRESSMODE = 1;
  19292. Texture.MIRROR_ADDRESSMODE = 2;
  19293. __decorate([
  19294. BABYLON.serialize()
  19295. ], Texture.prototype, "url", void 0);
  19296. __decorate([
  19297. BABYLON.serialize()
  19298. ], Texture.prototype, "uOffset", void 0);
  19299. __decorate([
  19300. BABYLON.serialize()
  19301. ], Texture.prototype, "vOffset", void 0);
  19302. __decorate([
  19303. BABYLON.serialize()
  19304. ], Texture.prototype, "uScale", void 0);
  19305. __decorate([
  19306. BABYLON.serialize()
  19307. ], Texture.prototype, "vScale", void 0);
  19308. __decorate([
  19309. BABYLON.serialize()
  19310. ], Texture.prototype, "uAng", void 0);
  19311. __decorate([
  19312. BABYLON.serialize()
  19313. ], Texture.prototype, "vAng", void 0);
  19314. __decorate([
  19315. BABYLON.serialize()
  19316. ], Texture.prototype, "wAng", void 0);
  19317. __decorate([
  19318. BABYLON.serialize()
  19319. ], Texture.prototype, "isBlocking", null);
  19320. BABYLON.Texture = Texture;
  19321. })(BABYLON || (BABYLON = {}));
  19322. //# sourceMappingURL=babylon.texture.js.map
  19323. var BABYLON;
  19324. (function (BABYLON) {
  19325. var _InstancesBatch = (function () {
  19326. function _InstancesBatch() {
  19327. this.mustReturn = false;
  19328. this.visibleInstances = new Array();
  19329. this.renderSelf = new Array();
  19330. }
  19331. return _InstancesBatch;
  19332. }());
  19333. BABYLON._InstancesBatch = _InstancesBatch;
  19334. var Mesh = (function (_super) {
  19335. __extends(Mesh, _super);
  19336. /**
  19337. * @constructor
  19338. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  19339. * @param {Scene} scene The scene to add this mesh to.
  19340. * @param {Node} parent The parent of this mesh, if it has one
  19341. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  19342. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  19343. * When false, achieved by calling a clone(), also passing False.
  19344. * This will make creation of children, recursive.
  19345. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  19346. */
  19347. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  19348. if (parent === void 0) { parent = null; }
  19349. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19350. var _this = _super.call(this, name, scene) || this;
  19351. // Events
  19352. /**
  19353. * An event triggered before rendering the mesh
  19354. * @type {BABYLON.Observable}
  19355. */
  19356. _this.onBeforeRenderObservable = new BABYLON.Observable();
  19357. /**
  19358. * An event triggered after rendering the mesh
  19359. * @type {BABYLON.Observable}
  19360. */
  19361. _this.onAfterRenderObservable = new BABYLON.Observable();
  19362. /**
  19363. * An event triggered before drawing the mesh
  19364. * @type {BABYLON.Observable}
  19365. */
  19366. _this.onBeforeDrawObservable = new BABYLON.Observable();
  19367. // Members
  19368. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19369. _this.instances = new Array();
  19370. _this._LODLevels = new Array();
  19371. _this._visibleInstances = {};
  19372. _this._renderIdForInstances = new Array();
  19373. _this._batchCache = new _InstancesBatch();
  19374. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  19375. _this._sideOrientation = Mesh._DEFAULTSIDE;
  19376. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  19377. // Will be used to save a source mesh reference, If any
  19378. _this._source = null;
  19379. if (source) {
  19380. // Source mesh
  19381. _this._source = source;
  19382. // Geometry
  19383. if (source._geometry) {
  19384. source._geometry.applyToMesh(_this);
  19385. }
  19386. // Deep copy
  19387. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  19388. // Parent
  19389. _this.parent = source.parent;
  19390. // Pivot
  19391. _this.setPivotMatrix(source.getPivotMatrix());
  19392. _this.id = name + "." + source.id;
  19393. // Material
  19394. _this.material = source.material;
  19395. var index;
  19396. if (!doNotCloneChildren) {
  19397. // Children
  19398. for (index = 0; index < scene.meshes.length; index++) {
  19399. var mesh = scene.meshes[index];
  19400. if (mesh.parent === source) {
  19401. // doNotCloneChildren is always going to be False
  19402. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  19403. }
  19404. }
  19405. }
  19406. // Physics clone
  19407. var physicsEngine = _this.getScene().getPhysicsEngine();
  19408. if (clonePhysicsImpostor && physicsEngine) {
  19409. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  19410. if (impostor) {
  19411. _this.physicsImpostor = impostor.clone(_this);
  19412. }
  19413. }
  19414. // Particles
  19415. for (index = 0; index < scene.particleSystems.length; index++) {
  19416. var system = scene.particleSystems[index];
  19417. if (system.emitter === source) {
  19418. system.clone(system.name, _this);
  19419. }
  19420. }
  19421. _this.computeWorldMatrix(true);
  19422. }
  19423. // Parent
  19424. if (parent !== null) {
  19425. _this.parent = parent;
  19426. }
  19427. return _this;
  19428. }
  19429. Object.defineProperty(Mesh, "FRONTSIDE", {
  19430. /**
  19431. * Mesh side orientation : usually the external or front surface
  19432. */
  19433. get: function () {
  19434. return Mesh._FRONTSIDE;
  19435. },
  19436. enumerable: true,
  19437. configurable: true
  19438. });
  19439. Object.defineProperty(Mesh, "BACKSIDE", {
  19440. /**
  19441. * Mesh side orientation : usually the internal or back surface
  19442. */
  19443. get: function () {
  19444. return Mesh._BACKSIDE;
  19445. },
  19446. enumerable: true,
  19447. configurable: true
  19448. });
  19449. Object.defineProperty(Mesh, "DOUBLESIDE", {
  19450. /**
  19451. * Mesh side orientation : both internal and external or front and back surfaces
  19452. */
  19453. get: function () {
  19454. return Mesh._DOUBLESIDE;
  19455. },
  19456. enumerable: true,
  19457. configurable: true
  19458. });
  19459. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  19460. /**
  19461. * Mesh side orientation : by default, `FRONTSIDE`
  19462. */
  19463. get: function () {
  19464. return Mesh._DEFAULTSIDE;
  19465. },
  19466. enumerable: true,
  19467. configurable: true
  19468. });
  19469. Object.defineProperty(Mesh, "NO_CAP", {
  19470. /**
  19471. * Mesh cap setting : no cap
  19472. */
  19473. get: function () {
  19474. return Mesh._NO_CAP;
  19475. },
  19476. enumerable: true,
  19477. configurable: true
  19478. });
  19479. Object.defineProperty(Mesh, "CAP_START", {
  19480. /**
  19481. * Mesh cap setting : one cap at the beginning of the mesh
  19482. */
  19483. get: function () {
  19484. return Mesh._CAP_START;
  19485. },
  19486. enumerable: true,
  19487. configurable: true
  19488. });
  19489. Object.defineProperty(Mesh, "CAP_END", {
  19490. /**
  19491. * Mesh cap setting : one cap at the end of the mesh
  19492. */
  19493. get: function () {
  19494. return Mesh._CAP_END;
  19495. },
  19496. enumerable: true,
  19497. configurable: true
  19498. });
  19499. Object.defineProperty(Mesh, "CAP_ALL", {
  19500. /**
  19501. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  19502. */
  19503. get: function () {
  19504. return Mesh._CAP_ALL;
  19505. },
  19506. enumerable: true,
  19507. configurable: true
  19508. });
  19509. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  19510. set: function (callback) {
  19511. if (this._onBeforeDrawObserver) {
  19512. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  19513. }
  19514. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  19515. },
  19516. enumerable: true,
  19517. configurable: true
  19518. });
  19519. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  19520. get: function () {
  19521. return this._morphTargetManager;
  19522. },
  19523. set: function (value) {
  19524. if (this._morphTargetManager === value) {
  19525. return;
  19526. }
  19527. this._morphTargetManager = value;
  19528. this._syncGeometryWithMorphTargetManager();
  19529. },
  19530. enumerable: true,
  19531. configurable: true
  19532. });
  19533. Object.defineProperty(Mesh.prototype, "source", {
  19534. get: function () {
  19535. return this._source;
  19536. },
  19537. enumerable: true,
  19538. configurable: true
  19539. });
  19540. // Methods
  19541. /**
  19542. * Returns the string "Mesh".
  19543. */
  19544. Mesh.prototype.getClassName = function () {
  19545. return "Mesh";
  19546. };
  19547. /**
  19548. * Returns a string.
  19549. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19550. */
  19551. Mesh.prototype.toString = function (fullDetails) {
  19552. var ret = _super.prototype.toString.call(this, fullDetails);
  19553. ret += ", n vertices: " + this.getTotalVertices();
  19554. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  19555. if (this.animations) {
  19556. for (var i = 0; i < this.animations.length; i++) {
  19557. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19558. }
  19559. }
  19560. if (fullDetails) {
  19561. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  19562. }
  19563. return ret;
  19564. };
  19565. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  19566. /**
  19567. * True if the mesh has some Levels Of Details (LOD).
  19568. * Returns a boolean.
  19569. */
  19570. get: function () {
  19571. return this._LODLevels.length > 0;
  19572. },
  19573. enumerable: true,
  19574. configurable: true
  19575. });
  19576. Mesh.prototype._sortLODLevels = function () {
  19577. this._LODLevels.sort(function (a, b) {
  19578. if (a.distance < b.distance) {
  19579. return 1;
  19580. }
  19581. if (a.distance > b.distance) {
  19582. return -1;
  19583. }
  19584. return 0;
  19585. });
  19586. };
  19587. /**
  19588. * Add a mesh as LOD level triggered at the given distance.
  19589. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19590. * @param {number} distance The distance from the center of the object to show this level
  19591. * @param {Mesh} mesh The mesh to be added as LOD level
  19592. * @return {Mesh} This mesh (for chaining)
  19593. */
  19594. Mesh.prototype.addLODLevel = function (distance, mesh) {
  19595. if (mesh && mesh._masterMesh) {
  19596. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  19597. return this;
  19598. }
  19599. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  19600. this._LODLevels.push(level);
  19601. if (mesh) {
  19602. mesh._masterMesh = this;
  19603. }
  19604. this._sortLODLevels();
  19605. return this;
  19606. };
  19607. /**
  19608. * Returns the LOD level mesh at the passed distance or null if not found.
  19609. * It is related to the method `addLODLevel(distance, mesh)`.
  19610. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19611. * Returns an object Mesh or `null`.
  19612. */
  19613. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  19614. for (var index = 0; index < this._LODLevels.length; index++) {
  19615. var level = this._LODLevels[index];
  19616. if (level.distance === distance) {
  19617. return level.mesh;
  19618. }
  19619. }
  19620. return null;
  19621. };
  19622. /**
  19623. * Remove a mesh from the LOD array
  19624. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19625. * @param {Mesh} mesh The mesh to be removed.
  19626. * @return {Mesh} This mesh (for chaining)
  19627. */
  19628. Mesh.prototype.removeLODLevel = function (mesh) {
  19629. for (var index = 0; index < this._LODLevels.length; index++) {
  19630. if (this._LODLevels[index].mesh === mesh) {
  19631. this._LODLevels.splice(index, 1);
  19632. if (mesh) {
  19633. mesh._masterMesh = null;
  19634. }
  19635. }
  19636. }
  19637. this._sortLODLevels();
  19638. return this;
  19639. };
  19640. /**
  19641. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  19642. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19643. */
  19644. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  19645. if (!this._LODLevels || this._LODLevels.length === 0) {
  19646. return this;
  19647. }
  19648. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  19649. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  19650. if (this.onLODLevelSelection) {
  19651. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  19652. }
  19653. return this;
  19654. }
  19655. for (var index = 0; index < this._LODLevels.length; index++) {
  19656. var level = this._LODLevels[index];
  19657. if (level.distance < distanceToCamera) {
  19658. if (level.mesh) {
  19659. level.mesh._preActivate();
  19660. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19661. }
  19662. if (this.onLODLevelSelection) {
  19663. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  19664. }
  19665. return level.mesh;
  19666. }
  19667. }
  19668. if (this.onLODLevelSelection) {
  19669. this.onLODLevelSelection(distanceToCamera, this, this);
  19670. }
  19671. return this;
  19672. };
  19673. Object.defineProperty(Mesh.prototype, "geometry", {
  19674. /**
  19675. * Returns the mesh internal Geometry object.
  19676. */
  19677. get: function () {
  19678. return this._geometry;
  19679. },
  19680. enumerable: true,
  19681. configurable: true
  19682. });
  19683. /**
  19684. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  19685. */
  19686. Mesh.prototype.getTotalVertices = function () {
  19687. if (!this._geometry) {
  19688. return 0;
  19689. }
  19690. return this._geometry.getTotalVertices();
  19691. };
  19692. /**
  19693. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  19694. * 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.
  19695. * You can force the copy with forceCopy === true
  19696. * Returns null if the mesh has no geometry or no vertex buffer.
  19697. * Possible `kind` values :
  19698. * - BABYLON.VertexBuffer.PositionKind
  19699. * - BABYLON.VertexBuffer.UVKind
  19700. * - BABYLON.VertexBuffer.UV2Kind
  19701. * - BABYLON.VertexBuffer.UV3Kind
  19702. * - BABYLON.VertexBuffer.UV4Kind
  19703. * - BABYLON.VertexBuffer.UV5Kind
  19704. * - BABYLON.VertexBuffer.UV6Kind
  19705. * - BABYLON.VertexBuffer.ColorKind
  19706. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19707. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19708. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19709. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19710. */
  19711. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  19712. if (!this._geometry) {
  19713. return null;
  19714. }
  19715. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  19716. };
  19717. /**
  19718. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  19719. * Returns `undefined` if the mesh has no geometry.
  19720. * Possible `kind` values :
  19721. * - BABYLON.VertexBuffer.PositionKind
  19722. * - BABYLON.VertexBuffer.UVKind
  19723. * - BABYLON.VertexBuffer.UV2Kind
  19724. * - BABYLON.VertexBuffer.UV3Kind
  19725. * - BABYLON.VertexBuffer.UV4Kind
  19726. * - BABYLON.VertexBuffer.UV5Kind
  19727. * - BABYLON.VertexBuffer.UV6Kind
  19728. * - BABYLON.VertexBuffer.ColorKind
  19729. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19730. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19731. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19732. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19733. */
  19734. Mesh.prototype.getVertexBuffer = function (kind) {
  19735. if (!this._geometry) {
  19736. return undefined;
  19737. }
  19738. return this._geometry.getVertexBuffer(kind);
  19739. };
  19740. /**
  19741. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  19742. * Possible `kind` values :
  19743. * - BABYLON.VertexBuffer.PositionKind
  19744. * - BABYLON.VertexBuffer.UVKind
  19745. * - BABYLON.VertexBuffer.UV2Kind
  19746. * - BABYLON.VertexBuffer.UV3Kind
  19747. * - BABYLON.VertexBuffer.UV4Kind
  19748. * - BABYLON.VertexBuffer.UV5Kind
  19749. * - BABYLON.VertexBuffer.UV6Kind
  19750. * - BABYLON.VertexBuffer.ColorKind
  19751. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19752. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19753. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19754. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19755. */
  19756. Mesh.prototype.isVerticesDataPresent = function (kind) {
  19757. if (!this._geometry) {
  19758. if (this._delayInfo) {
  19759. return this._delayInfo.indexOf(kind) !== -1;
  19760. }
  19761. return false;
  19762. }
  19763. return this._geometry.isVerticesDataPresent(kind);
  19764. };
  19765. /**
  19766. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  19767. * Possible `kind` values :
  19768. * - BABYLON.VertexBuffer.PositionKind
  19769. * - BABYLON.VertexBuffer.UVKind
  19770. * - BABYLON.VertexBuffer.UV2Kind
  19771. * - BABYLON.VertexBuffer.UV3Kind
  19772. * - BABYLON.VertexBuffer.UV4Kind
  19773. * - BABYLON.VertexBuffer.UV5Kind
  19774. * - BABYLON.VertexBuffer.UV6Kind
  19775. * - BABYLON.VertexBuffer.ColorKind
  19776. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19777. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19778. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19779. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19780. */
  19781. Mesh.prototype.getVerticesDataKinds = function () {
  19782. if (!this._geometry) {
  19783. var result = [];
  19784. if (this._delayInfo) {
  19785. this._delayInfo.forEach(function (kind, index, array) {
  19786. result.push(kind);
  19787. });
  19788. }
  19789. return result;
  19790. }
  19791. return this._geometry.getVerticesDataKinds();
  19792. };
  19793. /**
  19794. * Returns a positive integer : the total number of indices in this mesh geometry.
  19795. * Returns zero if the mesh has no geometry.
  19796. */
  19797. Mesh.prototype.getTotalIndices = function () {
  19798. if (!this._geometry) {
  19799. return 0;
  19800. }
  19801. return this._geometry.getTotalIndices();
  19802. };
  19803. /**
  19804. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  19805. * 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.
  19806. * Returns an empty array if the mesh has no geometry.
  19807. */
  19808. Mesh.prototype.getIndices = function (copyWhenShared) {
  19809. if (!this._geometry) {
  19810. return [];
  19811. }
  19812. return this._geometry.getIndices(copyWhenShared);
  19813. };
  19814. Object.defineProperty(Mesh.prototype, "isBlocked", {
  19815. get: function () {
  19816. return this._masterMesh !== null && this._masterMesh !== undefined;
  19817. },
  19818. enumerable: true,
  19819. configurable: true
  19820. });
  19821. /**
  19822. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  19823. */
  19824. Mesh.prototype.isReady = function () {
  19825. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19826. return false;
  19827. }
  19828. return _super.prototype.isReady.call(this);
  19829. };
  19830. /**
  19831. * Boolean : true if the mesh has been disposed.
  19832. */
  19833. Mesh.prototype.isDisposed = function () {
  19834. return this._isDisposed;
  19835. };
  19836. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  19837. get: function () {
  19838. return this._sideOrientation;
  19839. },
  19840. /**
  19841. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  19842. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  19843. */
  19844. set: function (sideO) {
  19845. this._sideOrientation = sideO;
  19846. },
  19847. enumerable: true,
  19848. configurable: true
  19849. });
  19850. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  19851. /**
  19852. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  19853. * This property is pertinent only for updatable parametric shapes.
  19854. */
  19855. get: function () {
  19856. return this._areNormalsFrozen;
  19857. },
  19858. enumerable: true,
  19859. configurable: true
  19860. });
  19861. /**
  19862. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19863. * It has no effect at all on other shapes.
  19864. * It prevents the mesh normals from being recomputed on next `positions` array update.
  19865. * Returns the Mesh.
  19866. */
  19867. Mesh.prototype.freezeNormals = function () {
  19868. this._areNormalsFrozen = true;
  19869. return this;
  19870. };
  19871. /**
  19872. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19873. * It has no effect at all on other shapes.
  19874. * It reactivates the mesh normals computation if it was previously frozen.
  19875. * Returns the Mesh.
  19876. */
  19877. Mesh.prototype.unfreezeNormals = function () {
  19878. this._areNormalsFrozen = false;
  19879. return this;
  19880. };
  19881. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  19882. /**
  19883. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  19884. */
  19885. set: function (count) {
  19886. this._overridenInstanceCount = count;
  19887. },
  19888. enumerable: true,
  19889. configurable: true
  19890. });
  19891. // Methods
  19892. Mesh.prototype._preActivate = function () {
  19893. var sceneRenderId = this.getScene().getRenderId();
  19894. if (this._preActivateId === sceneRenderId) {
  19895. return this;
  19896. }
  19897. this._preActivateId = sceneRenderId;
  19898. this._visibleInstances = null;
  19899. return this;
  19900. };
  19901. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  19902. if (this._visibleInstances) {
  19903. this._visibleInstances.intermediateDefaultRenderId = renderId;
  19904. }
  19905. return this;
  19906. };
  19907. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  19908. if (!this._visibleInstances) {
  19909. this._visibleInstances = {};
  19910. this._visibleInstances.defaultRenderId = renderId;
  19911. this._visibleInstances.selfDefaultRenderId = this._renderId;
  19912. }
  19913. if (!this._visibleInstances[renderId]) {
  19914. this._visibleInstances[renderId] = new Array();
  19915. }
  19916. this._visibleInstances[renderId].push(instance);
  19917. return this;
  19918. };
  19919. /**
  19920. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  19921. * This means the mesh underlying bounding box and sphere are recomputed.
  19922. * Returns the Mesh.
  19923. */
  19924. Mesh.prototype.refreshBoundingInfo = function () {
  19925. if (this._boundingInfo.isLocked) {
  19926. return;
  19927. }
  19928. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19929. if (data) {
  19930. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  19931. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19932. }
  19933. if (this.subMeshes) {
  19934. for (var index = 0; index < this.subMeshes.length; index++) {
  19935. this.subMeshes[index].refreshBoundingInfo();
  19936. }
  19937. }
  19938. this._updateBoundingInfo();
  19939. return this;
  19940. };
  19941. Mesh.prototype._createGlobalSubMesh = function () {
  19942. var totalVertices = this.getTotalVertices();
  19943. if (!totalVertices || !this.getIndices()) {
  19944. return null;
  19945. }
  19946. this.releaseSubMeshes();
  19947. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  19948. };
  19949. Mesh.prototype.subdivide = function (count) {
  19950. if (count < 1) {
  19951. return;
  19952. }
  19953. var totalIndices = this.getTotalIndices();
  19954. var subdivisionSize = (totalIndices / count) | 0;
  19955. var offset = 0;
  19956. // Ensure that subdivisionSize is a multiple of 3
  19957. while (subdivisionSize % 3 !== 0) {
  19958. subdivisionSize++;
  19959. }
  19960. this.releaseSubMeshes();
  19961. for (var index = 0; index < count; index++) {
  19962. if (offset >= totalIndices) {
  19963. break;
  19964. }
  19965. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  19966. offset += subdivisionSize;
  19967. }
  19968. this.synchronizeInstances();
  19969. };
  19970. /**
  19971. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19972. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19973. * The `data` are either a numeric array either a Float32Array.
  19974. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  19975. * 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).
  19976. * Note that a new underlying VertexBuffer object is created each call.
  19977. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19978. *
  19979. * Possible `kind` values :
  19980. * - BABYLON.VertexBuffer.PositionKind
  19981. * - BABYLON.VertexBuffer.UVKind
  19982. * - BABYLON.VertexBuffer.UV2Kind
  19983. * - BABYLON.VertexBuffer.UV3Kind
  19984. * - BABYLON.VertexBuffer.UV4Kind
  19985. * - BABYLON.VertexBuffer.UV5Kind
  19986. * - BABYLON.VertexBuffer.UV6Kind
  19987. * - BABYLON.VertexBuffer.ColorKind
  19988. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19989. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19990. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19991. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19992. *
  19993. * Returns the Mesh.
  19994. */
  19995. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  19996. if (!this._geometry) {
  19997. var vertexData = new BABYLON.VertexData();
  19998. vertexData.set(data, kind);
  19999. var scene = this.getScene();
  20000. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  20001. }
  20002. else {
  20003. this._geometry.setVerticesData(kind, data, updatable, stride);
  20004. }
  20005. return this;
  20006. };
  20007. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  20008. if (updatable === void 0) { updatable = true; }
  20009. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  20010. return;
  20011. }
  20012. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  20013. };
  20014. /**
  20015. * Sets the mesh VertexBuffer.
  20016. * Returns the Mesh.
  20017. */
  20018. Mesh.prototype.setVerticesBuffer = function (buffer) {
  20019. if (!this._geometry) {
  20020. var scene = this.getScene();
  20021. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  20022. }
  20023. this._geometry.setVerticesBuffer(buffer);
  20024. return this;
  20025. };
  20026. /**
  20027. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20028. * If the mesh has no geometry, it is simply returned as it is.
  20029. * The `data` are either a numeric array either a Float32Array.
  20030. * No new underlying VertexBuffer object is created.
  20031. * 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.
  20032. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  20033. *
  20034. * Possible `kind` values :
  20035. * - BABYLON.VertexBuffer.PositionKind
  20036. * - BABYLON.VertexBuffer.UVKind
  20037. * - BABYLON.VertexBuffer.UV2Kind
  20038. * - BABYLON.VertexBuffer.UV3Kind
  20039. * - BABYLON.VertexBuffer.UV4Kind
  20040. * - BABYLON.VertexBuffer.UV5Kind
  20041. * - BABYLON.VertexBuffer.UV6Kind
  20042. * - BABYLON.VertexBuffer.ColorKind
  20043. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20044. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20045. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20046. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20047. *
  20048. * Returns the Mesh.
  20049. */
  20050. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20051. if (!this._geometry) {
  20052. return;
  20053. }
  20054. if (!makeItUnique) {
  20055. this._geometry.updateVerticesData(kind, data, updateExtends);
  20056. }
  20057. else {
  20058. this.makeGeometryUnique();
  20059. this.updateVerticesData(kind, data, updateExtends, false);
  20060. }
  20061. return this;
  20062. };
  20063. /**
  20064. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  20065. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  20066. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  20067. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  20068. * Returns the Mesh.
  20069. */
  20070. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  20071. if (computeNormals === void 0) { computeNormals = true; }
  20072. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20073. positionFunction(positions);
  20074. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  20075. if (computeNormals) {
  20076. var indices = this.getIndices();
  20077. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20078. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20079. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  20080. }
  20081. return this;
  20082. };
  20083. /**
  20084. * Creates a un-shared specific occurence of the geometry for the mesh.
  20085. * Returns the Mesh.
  20086. */
  20087. Mesh.prototype.makeGeometryUnique = function () {
  20088. if (!this._geometry) {
  20089. return;
  20090. }
  20091. var oldGeometry = this._geometry;
  20092. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  20093. oldGeometry.releaseForMesh(this, true);
  20094. geometry.applyToMesh(this);
  20095. return this;
  20096. };
  20097. /**
  20098. * Sets the mesh indices.
  20099. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  20100. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20101. * This method creates a new index buffer each call.
  20102. * Returns the Mesh.
  20103. */
  20104. Mesh.prototype.setIndices = function (indices, totalVertices) {
  20105. if (!this._geometry) {
  20106. var vertexData = new BABYLON.VertexData();
  20107. vertexData.indices = indices;
  20108. var scene = this.getScene();
  20109. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  20110. }
  20111. else {
  20112. this._geometry.setIndices(indices, totalVertices);
  20113. }
  20114. return this;
  20115. };
  20116. /**
  20117. * Invert the geometry to move from a right handed system to a left handed one.
  20118. * Returns the Mesh.
  20119. */
  20120. Mesh.prototype.toLeftHanded = function () {
  20121. if (!this._geometry) {
  20122. return;
  20123. }
  20124. this._geometry.toLeftHanded();
  20125. return this;
  20126. };
  20127. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  20128. var engine = this.getScene().getEngine();
  20129. // Wireframe
  20130. var indexToBind;
  20131. if (this._unIndexed) {
  20132. indexToBind = null;
  20133. }
  20134. else {
  20135. switch (fillMode) {
  20136. case BABYLON.Material.PointFillMode:
  20137. indexToBind = null;
  20138. break;
  20139. case BABYLON.Material.WireFrameFillMode:
  20140. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  20141. break;
  20142. default:
  20143. case BABYLON.Material.TriangleFillMode:
  20144. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  20145. break;
  20146. }
  20147. }
  20148. // VBOs
  20149. this._geometry._bind(effect, indexToBind);
  20150. return this;
  20151. };
  20152. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  20153. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20154. return this;
  20155. }
  20156. this.onBeforeDrawObservable.notifyObservers(this);
  20157. var engine = this.getScene().getEngine();
  20158. // Draw order
  20159. switch (fillMode) {
  20160. case BABYLON.Material.PointFillMode:
  20161. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20162. break;
  20163. case BABYLON.Material.WireFrameFillMode:
  20164. if (this._unIndexed) {
  20165. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20166. }
  20167. else {
  20168. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  20169. }
  20170. break;
  20171. default:
  20172. if (this._unIndexed) {
  20173. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20174. }
  20175. else {
  20176. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  20177. }
  20178. }
  20179. return this;
  20180. };
  20181. /**
  20182. * Registers for this mesh a javascript function called just before the rendering process.
  20183. * This function is passed the current mesh.
  20184. * Return the Mesh.
  20185. */
  20186. Mesh.prototype.registerBeforeRender = function (func) {
  20187. this.onBeforeRenderObservable.add(func);
  20188. return this;
  20189. };
  20190. /**
  20191. * Disposes a previously registered javascript function called before the rendering.
  20192. * This function is passed the current mesh.
  20193. * Returns the Mesh.
  20194. */
  20195. Mesh.prototype.unregisterBeforeRender = function (func) {
  20196. this.onBeforeRenderObservable.removeCallback(func);
  20197. return this;
  20198. };
  20199. /**
  20200. * Registers for this mesh a javascript function called just after the rendering is complete.
  20201. * This function is passed the current mesh.
  20202. * Returns the Mesh.
  20203. */
  20204. Mesh.prototype.registerAfterRender = function (func) {
  20205. this.onAfterRenderObservable.add(func);
  20206. return this;
  20207. };
  20208. /**
  20209. * Disposes a previously registered javascript function called after the rendering.
  20210. * This function is passed the current mesh.
  20211. * Return the Mesh.
  20212. */
  20213. Mesh.prototype.unregisterAfterRender = function (func) {
  20214. this.onAfterRenderObservable.removeCallback(func);
  20215. return this;
  20216. };
  20217. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  20218. var scene = this.getScene();
  20219. this._batchCache.mustReturn = false;
  20220. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  20221. this._batchCache.visibleInstances[subMeshId] = null;
  20222. if (this._visibleInstances) {
  20223. var currentRenderId = scene.getRenderId();
  20224. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  20225. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  20226. var selfRenderId = this._renderId;
  20227. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  20228. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  20229. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  20230. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  20231. }
  20232. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  20233. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  20234. this._batchCache.mustReturn = true;
  20235. return this._batchCache;
  20236. }
  20237. if (currentRenderId !== selfRenderId) {
  20238. this._batchCache.renderSelf[subMeshId] = false;
  20239. }
  20240. }
  20241. this._renderIdForInstances[subMeshId] = currentRenderId;
  20242. }
  20243. return this._batchCache;
  20244. };
  20245. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  20246. var visibleInstances = batch.visibleInstances[subMesh._id];
  20247. var matricesCount = visibleInstances.length + 1;
  20248. var bufferSize = matricesCount * 16 * 4;
  20249. var currentInstancesBufferSize = this._instancesBufferSize;
  20250. var instancesBuffer = this._instancesBuffer;
  20251. while (this._instancesBufferSize < bufferSize) {
  20252. this._instancesBufferSize *= 2;
  20253. }
  20254. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  20255. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  20256. }
  20257. var offset = 0;
  20258. var instancesCount = 0;
  20259. var world = this.getWorldMatrix();
  20260. if (batch.renderSelf[subMesh._id]) {
  20261. world.copyToArray(this._instancesData, offset);
  20262. offset += 16;
  20263. instancesCount++;
  20264. }
  20265. if (visibleInstances) {
  20266. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  20267. var instance = visibleInstances[instanceIndex];
  20268. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  20269. offset += 16;
  20270. instancesCount++;
  20271. }
  20272. }
  20273. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  20274. if (instancesBuffer) {
  20275. instancesBuffer.dispose();
  20276. }
  20277. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  20278. this._instancesBuffer = instancesBuffer;
  20279. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  20280. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  20281. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  20282. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  20283. }
  20284. else {
  20285. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  20286. }
  20287. this.geometry._bind(effect);
  20288. this._draw(subMesh, fillMode, instancesCount);
  20289. engine.unbindInstanceAttributes();
  20290. return this;
  20291. };
  20292. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  20293. var scene = this.getScene();
  20294. var engine = scene.getEngine();
  20295. if (hardwareInstancedRendering) {
  20296. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  20297. }
  20298. else {
  20299. if (batch.renderSelf[subMesh._id]) {
  20300. // Draw
  20301. if (onBeforeDraw) {
  20302. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  20303. }
  20304. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  20305. }
  20306. if (batch.visibleInstances[subMesh._id]) {
  20307. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20308. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20309. // World
  20310. var world = instance.getWorldMatrix();
  20311. if (onBeforeDraw) {
  20312. onBeforeDraw(true, world, effectiveMaterial);
  20313. }
  20314. // Draw
  20315. this._draw(subMesh, fillMode);
  20316. }
  20317. }
  20318. }
  20319. return this;
  20320. };
  20321. /**
  20322. * Triggers the draw call for the mesh.
  20323. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  20324. * Returns the Mesh.
  20325. */
  20326. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  20327. var scene = this.getScene();
  20328. // Managing instances
  20329. var batch = this._getInstancesRenderList(subMesh._id);
  20330. if (batch.mustReturn) {
  20331. return this;
  20332. }
  20333. // Checking geometry state
  20334. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20335. return this;
  20336. }
  20337. var callbackIndex;
  20338. this.onBeforeRenderObservable.notifyObservers(this);
  20339. var engine = scene.getEngine();
  20340. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  20341. // Material
  20342. var effectiveMaterial = subMesh.getMaterial();
  20343. if (!effectiveMaterial) {
  20344. return this;
  20345. }
  20346. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20347. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  20348. return this;
  20349. }
  20350. }
  20351. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  20352. return this;
  20353. }
  20354. // Outline - step 1
  20355. var savedDepthWrite = engine.getDepthWrite();
  20356. if (this.renderOutline) {
  20357. engine.setDepthWrite(false);
  20358. scene.getOutlineRenderer().render(subMesh, batch);
  20359. engine.setDepthWrite(savedDepthWrite);
  20360. }
  20361. var effect;
  20362. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20363. effect = subMesh.effect;
  20364. }
  20365. else {
  20366. effect = effectiveMaterial.getEffect();
  20367. }
  20368. effectiveMaterial._preBind(effect);
  20369. // Bind
  20370. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  20371. this._bind(subMesh, effect, fillMode);
  20372. var world = this.getWorldMatrix();
  20373. if (effectiveMaterial.storeEffectOnSubMeshes) {
  20374. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  20375. }
  20376. else {
  20377. effectiveMaterial.bind(world, this);
  20378. }
  20379. // Alpha mode
  20380. if (enableAlphaMode) {
  20381. engine.setAlphaMode(effectiveMaterial.alphaMode);
  20382. }
  20383. // Draw
  20384. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  20385. // Unbind
  20386. effectiveMaterial.unbind();
  20387. // Outline - step 2
  20388. if (this.renderOutline && savedDepthWrite) {
  20389. engine.setDepthWrite(true);
  20390. engine.setColorWrite(false);
  20391. scene.getOutlineRenderer().render(subMesh, batch);
  20392. engine.setColorWrite(true);
  20393. }
  20394. // Overlay
  20395. if (this.renderOverlay) {
  20396. var currentMode = engine.getAlphaMode();
  20397. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20398. scene.getOutlineRenderer().render(subMesh, batch, true);
  20399. engine.setAlphaMode(currentMode);
  20400. }
  20401. this.onAfterRenderObservable.notifyObservers(this);
  20402. return this;
  20403. };
  20404. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  20405. if (isInstance) {
  20406. effectiveMaterial.bindOnlyWorldMatrix(world);
  20407. }
  20408. return this;
  20409. };
  20410. /**
  20411. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  20412. */
  20413. Mesh.prototype.getEmittedParticleSystems = function () {
  20414. var results = new Array();
  20415. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20416. var particleSystem = this.getScene().particleSystems[index];
  20417. if (particleSystem.emitter === this) {
  20418. results.push(particleSystem);
  20419. }
  20420. }
  20421. return results;
  20422. };
  20423. /**
  20424. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  20425. */
  20426. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  20427. var results = new Array();
  20428. var descendants = this.getDescendants();
  20429. descendants.push(this);
  20430. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20431. var particleSystem = this.getScene().particleSystems[index];
  20432. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  20433. results.push(particleSystem);
  20434. }
  20435. }
  20436. return results;
  20437. };
  20438. Mesh.prototype._checkDelayState = function () {
  20439. var scene = this.getScene();
  20440. if (this._geometry) {
  20441. this._geometry.load(scene);
  20442. }
  20443. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20444. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  20445. this._queueLoad(this, scene);
  20446. }
  20447. return this;
  20448. };
  20449. Mesh.prototype._queueLoad = function (mesh, scene) {
  20450. var _this = this;
  20451. scene._addPendingData(mesh);
  20452. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  20453. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  20454. if (data instanceof ArrayBuffer) {
  20455. _this._delayLoadingFunction(data, _this);
  20456. }
  20457. else {
  20458. _this._delayLoadingFunction(JSON.parse(data), _this);
  20459. }
  20460. _this.instances.forEach(function (instance) {
  20461. instance._syncSubMeshes();
  20462. });
  20463. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20464. scene._removePendingData(_this);
  20465. }, function () { }, scene.database, getBinaryData);
  20466. return this;
  20467. };
  20468. /**
  20469. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  20470. */
  20471. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  20472. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20473. return false;
  20474. }
  20475. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  20476. return false;
  20477. }
  20478. this._checkDelayState();
  20479. return true;
  20480. };
  20481. /**
  20482. * Sets the mesh material by the material or multiMaterial `id` property.
  20483. * The material `id` is a string identifying the material or the multiMaterial.
  20484. * This method returns the Mesh.
  20485. */
  20486. Mesh.prototype.setMaterialByID = function (id) {
  20487. var materials = this.getScene().materials;
  20488. var index;
  20489. for (index = materials.length - 1; index > -1; index--) {
  20490. if (materials[index].id === id) {
  20491. this.material = materials[index];
  20492. return this;
  20493. }
  20494. }
  20495. // Multi
  20496. var multiMaterials = this.getScene().multiMaterials;
  20497. for (index = multiMaterials.length - 1; index > -1; index--) {
  20498. if (multiMaterials[index].id === id) {
  20499. this.material = multiMaterials[index];
  20500. return this;
  20501. }
  20502. }
  20503. return this;
  20504. };
  20505. /**
  20506. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  20507. */
  20508. Mesh.prototype.getAnimatables = function () {
  20509. var results = [];
  20510. if (this.material) {
  20511. results.push(this.material);
  20512. }
  20513. if (this.skeleton) {
  20514. results.push(this.skeleton);
  20515. }
  20516. return results;
  20517. };
  20518. /**
  20519. * Modifies the mesh geometry according to the passed transformation matrix.
  20520. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  20521. * The mesh normals are modified accordingly the same transformation.
  20522. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20523. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20524. * Returns the Mesh.
  20525. */
  20526. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  20527. // Position
  20528. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20529. return this;
  20530. }
  20531. var submeshes = this.subMeshes.splice(0);
  20532. this._resetPointsArrayCache();
  20533. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20534. var temp = [];
  20535. var index;
  20536. for (index = 0; index < data.length; index += 3) {
  20537. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  20538. }
  20539. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  20540. // Normals
  20541. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20542. return this;
  20543. }
  20544. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20545. temp = [];
  20546. for (index = 0; index < data.length; index += 3) {
  20547. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  20548. }
  20549. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  20550. // flip faces?
  20551. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  20552. this.flipFaces();
  20553. }
  20554. // Restore submeshes
  20555. this.releaseSubMeshes();
  20556. this.subMeshes = submeshes;
  20557. return this;
  20558. };
  20559. /**
  20560. * Modifies the mesh geometry according to its own current World Matrix.
  20561. * The mesh World Matrix is then reset.
  20562. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  20563. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20564. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20565. * Returns the Mesh.
  20566. */
  20567. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  20568. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  20569. this.scaling.copyFromFloats(1, 1, 1);
  20570. this.position.copyFromFloats(0, 0, 0);
  20571. this.rotation.copyFromFloats(0, 0, 0);
  20572. //only if quaternion is already set
  20573. if (this.rotationQuaternion) {
  20574. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  20575. }
  20576. this._worldMatrix = BABYLON.Matrix.Identity();
  20577. return this;
  20578. };
  20579. Object.defineProperty(Mesh.prototype, "_positions", {
  20580. // Cache
  20581. get: function () {
  20582. if (this._geometry) {
  20583. return this._geometry._positions;
  20584. }
  20585. return null;
  20586. },
  20587. enumerable: true,
  20588. configurable: true
  20589. });
  20590. Mesh.prototype._resetPointsArrayCache = function () {
  20591. if (this._geometry) {
  20592. this._geometry._resetPointsArrayCache();
  20593. }
  20594. return this;
  20595. };
  20596. Mesh.prototype._generatePointsArray = function () {
  20597. if (this._geometry) {
  20598. return this._geometry._generatePointsArray();
  20599. }
  20600. return false;
  20601. };
  20602. /**
  20603. * Returns a new Mesh object generated from the current mesh properties.
  20604. * This method must not get confused with createInstance().
  20605. * The parameter `name` is a string, the name given to the new mesh.
  20606. * The optional parameter `newParent` can be any Node object (default `null`).
  20607. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  20608. * 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.
  20609. */
  20610. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  20611. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20612. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  20613. };
  20614. /**
  20615. * Disposes the mesh.
  20616. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  20617. */
  20618. Mesh.prototype.dispose = function (doNotRecurse) {
  20619. var _this = this;
  20620. this.morphTargetManager = undefined;
  20621. if (this._geometry) {
  20622. this._geometry.releaseForMesh(this, true);
  20623. }
  20624. // Sources
  20625. var meshes = this.getScene().meshes;
  20626. meshes.forEach(function (mesh) {
  20627. if (mesh._source && mesh._source === _this) {
  20628. mesh._source = null;
  20629. }
  20630. });
  20631. this._source = null;
  20632. // Instances
  20633. if (this._instancesBuffer) {
  20634. this._instancesBuffer.dispose();
  20635. this._instancesBuffer = null;
  20636. }
  20637. while (this.instances.length) {
  20638. this.instances[0].dispose();
  20639. }
  20640. // Highlight layers.
  20641. var highlightLayers = this.getScene().highlightLayers;
  20642. for (var i = 0; i < highlightLayers.length; i++) {
  20643. var highlightLayer = highlightLayers[i];
  20644. if (highlightLayer) {
  20645. highlightLayer.removeMesh(this);
  20646. highlightLayer.removeExcludedMesh(this);
  20647. }
  20648. }
  20649. _super.prototype.dispose.call(this, doNotRecurse);
  20650. };
  20651. /**
  20652. * Modifies the mesh geometry according to a displacement map.
  20653. * 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.
  20654. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20655. * This method returns nothing.
  20656. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  20657. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20658. * 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.
  20659. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  20660. * The parameter `uvScale` is an optional vector2 used to scale UV.
  20661. *
  20662. * Returns the Mesh.
  20663. */
  20664. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  20665. var _this = this;
  20666. var scene = this.getScene();
  20667. var onload = function (img) {
  20668. // Getting height map data
  20669. var canvas = document.createElement("canvas");
  20670. var context = canvas.getContext("2d");
  20671. var heightMapWidth = img.width;
  20672. var heightMapHeight = img.height;
  20673. canvas.width = heightMapWidth;
  20674. canvas.height = heightMapHeight;
  20675. context.drawImage(img, 0, 0);
  20676. // Create VertexData from map data
  20677. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20678. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  20679. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  20680. //execute success callback, if set
  20681. if (onSuccess) {
  20682. onSuccess(_this);
  20683. }
  20684. };
  20685. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20686. return this;
  20687. };
  20688. /**
  20689. * Modifies the mesh geometry according to a displacementMap buffer.
  20690. * 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.
  20691. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20692. * This method returns nothing.
  20693. * 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.
  20694. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  20695. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20696. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  20697. * The parameter `uvScale` is an optional vector2 used to scale UV.
  20698. *
  20699. * Returns the Mesh.
  20700. */
  20701. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  20702. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  20703. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  20704. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20705. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  20706. return this;
  20707. }
  20708. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20709. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20710. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20711. var position = BABYLON.Vector3.Zero();
  20712. var normal = BABYLON.Vector3.Zero();
  20713. var uv = BABYLON.Vector2.Zero();
  20714. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  20715. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  20716. for (var index = 0; index < positions.length; index += 3) {
  20717. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  20718. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  20719. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  20720. // Compute height
  20721. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  20722. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  20723. var pos = (u + v * heightMapWidth) * 4;
  20724. var r = buffer[pos] / 255.0;
  20725. var g = buffer[pos + 1] / 255.0;
  20726. var b = buffer[pos + 2] / 255.0;
  20727. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20728. normal.normalize();
  20729. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  20730. position = position.add(normal);
  20731. position.toArray(positions, index);
  20732. }
  20733. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  20734. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  20735. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20736. return this;
  20737. };
  20738. /**
  20739. * Modify the mesh to get a flat shading rendering.
  20740. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  20741. * This method returns the Mesh.
  20742. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  20743. */
  20744. Mesh.prototype.convertToFlatShadedMesh = function () {
  20745. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  20746. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20747. var kinds = this.getVerticesDataKinds();
  20748. var vbs = [];
  20749. var data = [];
  20750. var newdata = [];
  20751. var updatableNormals = false;
  20752. var kindIndex;
  20753. var kind;
  20754. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20755. kind = kinds[kindIndex];
  20756. var vertexBuffer = this.getVertexBuffer(kind);
  20757. if (kind === BABYLON.VertexBuffer.NormalKind) {
  20758. updatableNormals = vertexBuffer.isUpdatable();
  20759. kinds.splice(kindIndex, 1);
  20760. kindIndex--;
  20761. continue;
  20762. }
  20763. vbs[kind] = vertexBuffer;
  20764. data[kind] = vbs[kind].getData();
  20765. newdata[kind] = [];
  20766. }
  20767. // Save previous submeshes
  20768. var previousSubmeshes = this.subMeshes.slice(0);
  20769. var indices = this.getIndices();
  20770. var totalIndices = this.getTotalIndices();
  20771. // Generating unique vertices per face
  20772. var index;
  20773. for (index = 0; index < totalIndices; index++) {
  20774. var vertexIndex = indices[index];
  20775. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20776. kind = kinds[kindIndex];
  20777. var stride = vbs[kind].getStrideSize();
  20778. for (var offset = 0; offset < stride; offset++) {
  20779. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20780. }
  20781. }
  20782. }
  20783. // Updating faces & normal
  20784. var normals = [];
  20785. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  20786. for (index = 0; index < totalIndices; index += 3) {
  20787. indices[index] = index;
  20788. indices[index + 1] = index + 1;
  20789. indices[index + 2] = index + 2;
  20790. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  20791. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  20792. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  20793. var p1p2 = p1.subtract(p2);
  20794. var p3p2 = p3.subtract(p2);
  20795. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20796. // Store same normals for every vertex
  20797. for (var localIndex = 0; localIndex < 3; localIndex++) {
  20798. normals.push(normal.x);
  20799. normals.push(normal.y);
  20800. normals.push(normal.z);
  20801. }
  20802. }
  20803. this.setIndices(indices);
  20804. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  20805. // Updating vertex buffers
  20806. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20807. kind = kinds[kindIndex];
  20808. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20809. }
  20810. // Updating submeshes
  20811. this.releaseSubMeshes();
  20812. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20813. var previousOne = previousSubmeshes[submeshIndex];
  20814. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20815. }
  20816. this.synchronizeInstances();
  20817. return this;
  20818. };
  20819. /**
  20820. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  20821. * In other words, more vertices, no more indices and a single bigger VBO.
  20822. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  20823. * Returns the Mesh.
  20824. */
  20825. Mesh.prototype.convertToUnIndexedMesh = function () {
  20826. /// <summary>Remove indices by unfolding faces into buffers</summary>
  20827. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20828. var kinds = this.getVerticesDataKinds();
  20829. var vbs = [];
  20830. var data = [];
  20831. var newdata = [];
  20832. var updatableNormals = false;
  20833. var kindIndex;
  20834. var kind;
  20835. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20836. kind = kinds[kindIndex];
  20837. var vertexBuffer = this.getVertexBuffer(kind);
  20838. vbs[kind] = vertexBuffer;
  20839. data[kind] = vbs[kind].getData();
  20840. newdata[kind] = [];
  20841. }
  20842. // Save previous submeshes
  20843. var previousSubmeshes = this.subMeshes.slice(0);
  20844. var indices = this.getIndices();
  20845. var totalIndices = this.getTotalIndices();
  20846. // Generating unique vertices per face
  20847. var index;
  20848. for (index = 0; index < totalIndices; index++) {
  20849. var vertexIndex = indices[index];
  20850. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20851. kind = kinds[kindIndex];
  20852. var stride = vbs[kind].getStrideSize();
  20853. for (var offset = 0; offset < stride; offset++) {
  20854. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20855. }
  20856. }
  20857. }
  20858. // Updating indices
  20859. for (index = 0; index < totalIndices; index += 3) {
  20860. indices[index] = index;
  20861. indices[index + 1] = index + 1;
  20862. indices[index + 2] = index + 2;
  20863. }
  20864. this.setIndices(indices);
  20865. // Updating vertex buffers
  20866. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20867. kind = kinds[kindIndex];
  20868. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20869. }
  20870. // Updating submeshes
  20871. this.releaseSubMeshes();
  20872. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20873. var previousOne = previousSubmeshes[submeshIndex];
  20874. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20875. }
  20876. this._unIndexed = true;
  20877. this.synchronizeInstances();
  20878. return this;
  20879. };
  20880. /**
  20881. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  20882. * This method returns the Mesh.
  20883. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  20884. */
  20885. Mesh.prototype.flipFaces = function (flipNormals) {
  20886. if (flipNormals === void 0) { flipNormals = false; }
  20887. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  20888. var i;
  20889. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20890. for (i = 0; i < vertex_data.normals.length; i++) {
  20891. vertex_data.normals[i] *= -1;
  20892. }
  20893. }
  20894. var temp;
  20895. for (i = 0; i < vertex_data.indices.length; i += 3) {
  20896. // reassign indices
  20897. temp = vertex_data.indices[i + 1];
  20898. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  20899. vertex_data.indices[i + 2] = temp;
  20900. }
  20901. vertex_data.applyToMesh(this);
  20902. return this;
  20903. };
  20904. // Instances
  20905. /**
  20906. * Creates a new InstancedMesh object from the mesh model.
  20907. * An instance shares the same properties and the same material than its model.
  20908. * Only these properties of each instance can then be set individually :
  20909. * - position
  20910. * - rotation
  20911. * - rotationQuaternion
  20912. * - setPivotMatrix
  20913. * - scaling
  20914. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  20915. * Warning : this method is not supported for Line mesh and LineSystem
  20916. */
  20917. Mesh.prototype.createInstance = function (name) {
  20918. return new BABYLON.InstancedMesh(name, this);
  20919. };
  20920. /**
  20921. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  20922. * After this call, all the mesh instances have the same submeshes than the current mesh.
  20923. * This method returns the Mesh.
  20924. */
  20925. Mesh.prototype.synchronizeInstances = function () {
  20926. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  20927. var instance = this.instances[instanceIndex];
  20928. instance._syncSubMeshes();
  20929. }
  20930. return this;
  20931. };
  20932. /**
  20933. * Simplify the mesh according to the given array of settings.
  20934. * Function will return immediately and will simplify async. It returns the Mesh.
  20935. * @param settings a collection of simplification settings.
  20936. * @param parallelProcessing should all levels calculate parallel or one after the other.
  20937. * @param type the type of simplification to run.
  20938. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  20939. */
  20940. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  20941. if (parallelProcessing === void 0) { parallelProcessing = true; }
  20942. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  20943. this.getScene().simplificationQueue.addTask({
  20944. settings: settings,
  20945. parallelProcessing: parallelProcessing,
  20946. mesh: this,
  20947. simplificationType: simplificationType,
  20948. successCallback: successCallback
  20949. });
  20950. return this;
  20951. };
  20952. /**
  20953. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  20954. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  20955. * This should be used together with the simplification to avoid disappearing triangles.
  20956. * Returns the Mesh.
  20957. * @param successCallback an optional success callback to be called after the optimization finished.
  20958. */
  20959. Mesh.prototype.optimizeIndices = function (successCallback) {
  20960. var _this = this;
  20961. var indices = this.getIndices();
  20962. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20963. var vectorPositions = [];
  20964. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  20965. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  20966. }
  20967. var dupes = [];
  20968. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  20969. var realPos = vectorPositions.length - 1 - iteration;
  20970. var testedPosition = vectorPositions[realPos];
  20971. for (var j = 0; j < realPos; ++j) {
  20972. var againstPosition = vectorPositions[j];
  20973. if (testedPosition.equals(againstPosition)) {
  20974. dupes[realPos] = j;
  20975. break;
  20976. }
  20977. }
  20978. }, function () {
  20979. for (var i = 0; i < indices.length; ++i) {
  20980. indices[i] = dupes[indices[i]] || indices[i];
  20981. }
  20982. //indices are now reordered
  20983. var originalSubMeshes = _this.subMeshes.slice(0);
  20984. _this.setIndices(indices);
  20985. _this.subMeshes = originalSubMeshes;
  20986. if (successCallback) {
  20987. successCallback(_this);
  20988. }
  20989. });
  20990. return this;
  20991. };
  20992. Mesh.prototype.serialize = function (serializationObject) {
  20993. serializationObject.name = this.name;
  20994. serializationObject.id = this.id;
  20995. serializationObject.type = this.getClassName();
  20996. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  20997. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20998. }
  20999. serializationObject.position = this.position.asArray();
  21000. if (this.rotationQuaternion) {
  21001. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  21002. }
  21003. else if (this.rotation) {
  21004. serializationObject.rotation = this.rotation.asArray();
  21005. }
  21006. serializationObject.scaling = this.scaling.asArray();
  21007. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  21008. serializationObject.isEnabled = this.isEnabled();
  21009. serializationObject.isVisible = this.isVisible;
  21010. serializationObject.infiniteDistance = this.infiniteDistance;
  21011. serializationObject.pickable = this.isPickable;
  21012. serializationObject.receiveShadows = this.receiveShadows;
  21013. serializationObject.billboardMode = this.billboardMode;
  21014. serializationObject.visibility = this.visibility;
  21015. serializationObject.checkCollisions = this.checkCollisions;
  21016. serializationObject.isBlocker = this.isBlocker;
  21017. // Parent
  21018. if (this.parent) {
  21019. serializationObject.parentId = this.parent.id;
  21020. }
  21021. // Geometry
  21022. var geometry = this._geometry;
  21023. if (geometry) {
  21024. var geometryId = geometry.id;
  21025. serializationObject.geometryId = geometryId;
  21026. // SubMeshes
  21027. serializationObject.subMeshes = [];
  21028. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  21029. var subMesh = this.subMeshes[subIndex];
  21030. serializationObject.subMeshes.push({
  21031. materialIndex: subMesh.materialIndex,
  21032. verticesStart: subMesh.verticesStart,
  21033. verticesCount: subMesh.verticesCount,
  21034. indexStart: subMesh.indexStart,
  21035. indexCount: subMesh.indexCount
  21036. });
  21037. }
  21038. }
  21039. // Material
  21040. if (this.material) {
  21041. serializationObject.materialId = this.material.id;
  21042. }
  21043. else {
  21044. this.material = null;
  21045. }
  21046. // Morph targets
  21047. if (this.morphTargetManager) {
  21048. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  21049. }
  21050. // Skeleton
  21051. if (this.skeleton) {
  21052. serializationObject.skeletonId = this.skeleton.id;
  21053. }
  21054. // Physics
  21055. //TODO implement correct serialization for physics impostors.
  21056. if (this.getPhysicsImpostor()) {
  21057. var impostor = this.getPhysicsImpostor();
  21058. serializationObject.physicsMass = impostor.getParam("mass");
  21059. serializationObject.physicsFriction = impostor.getParam("friction");
  21060. serializationObject.physicsRestitution = impostor.getParam("mass");
  21061. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  21062. }
  21063. // Metadata
  21064. if (this.metadata) {
  21065. serializationObject.metadata = this.metadata;
  21066. }
  21067. // Instances
  21068. serializationObject.instances = [];
  21069. for (var index = 0; index < this.instances.length; index++) {
  21070. var instance = this.instances[index];
  21071. var serializationInstance = {
  21072. name: instance.name,
  21073. position: instance.position.asArray(),
  21074. scaling: instance.scaling.asArray()
  21075. };
  21076. if (instance.rotationQuaternion) {
  21077. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  21078. }
  21079. else if (instance.rotation) {
  21080. serializationInstance.rotation = instance.rotation.asArray();
  21081. }
  21082. serializationObject.instances.push(serializationInstance);
  21083. // Animations
  21084. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  21085. serializationInstance.ranges = instance.serializeAnimationRanges();
  21086. }
  21087. //
  21088. // Animations
  21089. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21090. serializationObject.ranges = this.serializeAnimationRanges();
  21091. // Layer mask
  21092. serializationObject.layerMask = this.layerMask;
  21093. // Alpha
  21094. serializationObject.alphaIndex = this.alphaIndex;
  21095. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  21096. // Overlay
  21097. serializationObject.overlayAlpha = this.overlayAlpha;
  21098. serializationObject.overlayColor = this.overlayColor.asArray();
  21099. serializationObject.renderOverlay = this.renderOverlay;
  21100. // Fog
  21101. serializationObject.applyFog = this.applyFog;
  21102. // Action Manager
  21103. if (this.actionManager) {
  21104. serializationObject.actions = this.actionManager.serialize(this.name);
  21105. }
  21106. };
  21107. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  21108. if (!this.geometry) {
  21109. return;
  21110. }
  21111. this._markSubMeshesAsAttributesDirty();
  21112. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  21113. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  21114. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  21115. this.morphTargetManager = undefined;
  21116. return;
  21117. }
  21118. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  21119. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  21120. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  21121. if (morphTarget.hasNormals) {
  21122. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  21123. }
  21124. if (morphTarget.hasTangents) {
  21125. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  21126. }
  21127. }
  21128. }
  21129. else {
  21130. var index = 0;
  21131. // Positions
  21132. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  21133. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  21134. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  21135. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  21136. }
  21137. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  21138. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  21139. }
  21140. index++;
  21141. }
  21142. }
  21143. };
  21144. // Statics
  21145. /**
  21146. * Returns a new Mesh object what is a deep copy of the passed mesh.
  21147. * The parameter `parsedMesh` is the mesh to be copied.
  21148. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  21149. */
  21150. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  21151. var mesh;
  21152. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  21153. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  21154. }
  21155. else {
  21156. mesh = new Mesh(parsedMesh.name, scene);
  21157. }
  21158. mesh.id = parsedMesh.id;
  21159. if (BABYLON.Tags) {
  21160. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  21161. }
  21162. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  21163. if (parsedMesh.metadata !== undefined) {
  21164. mesh.metadata = parsedMesh.metadata;
  21165. }
  21166. if (parsedMesh.rotationQuaternion) {
  21167. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  21168. }
  21169. else if (parsedMesh.rotation) {
  21170. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  21171. }
  21172. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  21173. if (parsedMesh.localMatrix) {
  21174. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  21175. }
  21176. else if (parsedMesh.pivotMatrix) {
  21177. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  21178. }
  21179. mesh.setEnabled(parsedMesh.isEnabled);
  21180. mesh.isVisible = parsedMesh.isVisible;
  21181. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  21182. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  21183. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  21184. if (parsedMesh.applyFog !== undefined) {
  21185. mesh.applyFog = parsedMesh.applyFog;
  21186. }
  21187. if (parsedMesh.pickable !== undefined) {
  21188. mesh.isPickable = parsedMesh.pickable;
  21189. }
  21190. if (parsedMesh.alphaIndex !== undefined) {
  21191. mesh.alphaIndex = parsedMesh.alphaIndex;
  21192. }
  21193. mesh.receiveShadows = parsedMesh.receiveShadows;
  21194. mesh.billboardMode = parsedMesh.billboardMode;
  21195. if (parsedMesh.visibility !== undefined) {
  21196. mesh.visibility = parsedMesh.visibility;
  21197. }
  21198. mesh.checkCollisions = parsedMesh.checkCollisions;
  21199. if (parsedMesh.isBlocker !== undefined) {
  21200. mesh.isBlocker = parsedMesh.isBlocker;
  21201. }
  21202. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  21203. // freezeWorldMatrix
  21204. if (parsedMesh.freezeWorldMatrix) {
  21205. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  21206. }
  21207. // Parent
  21208. if (parsedMesh.parentId) {
  21209. mesh._waitingParentId = parsedMesh.parentId;
  21210. }
  21211. // Actions
  21212. if (parsedMesh.actions !== undefined) {
  21213. mesh._waitingActions = parsedMesh.actions;
  21214. }
  21215. // Overlay
  21216. if (parsedMesh.overlayAlpha !== undefined) {
  21217. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  21218. }
  21219. if (parsedMesh.overlayColor !== undefined) {
  21220. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  21221. }
  21222. if (parsedMesh.renderOverlay !== undefined) {
  21223. mesh.renderOverlay = parsedMesh.renderOverlay;
  21224. }
  21225. // Geometry
  21226. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  21227. if (parsedMesh.delayLoadingFile) {
  21228. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21229. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  21230. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  21231. if (parsedMesh._binaryInfo) {
  21232. mesh._binaryInfo = parsedMesh._binaryInfo;
  21233. }
  21234. mesh._delayInfo = [];
  21235. if (parsedMesh.hasUVs) {
  21236. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  21237. }
  21238. if (parsedMesh.hasUVs2) {
  21239. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  21240. }
  21241. if (parsedMesh.hasUVs3) {
  21242. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  21243. }
  21244. if (parsedMesh.hasUVs4) {
  21245. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  21246. }
  21247. if (parsedMesh.hasUVs5) {
  21248. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  21249. }
  21250. if (parsedMesh.hasUVs6) {
  21251. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  21252. }
  21253. if (parsedMesh.hasColors) {
  21254. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  21255. }
  21256. if (parsedMesh.hasMatricesIndices) {
  21257. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  21258. }
  21259. if (parsedMesh.hasMatricesWeights) {
  21260. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  21261. }
  21262. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  21263. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  21264. mesh._checkDelayState();
  21265. }
  21266. }
  21267. else {
  21268. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  21269. }
  21270. // Material
  21271. if (parsedMesh.materialId) {
  21272. mesh.setMaterialByID(parsedMesh.materialId);
  21273. }
  21274. else {
  21275. mesh.material = null;
  21276. }
  21277. // Morph targets
  21278. if (parsedMesh.morphTargetManagerId > -1) {
  21279. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  21280. }
  21281. // Skeleton
  21282. if (parsedMesh.skeletonId > -1) {
  21283. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  21284. if (parsedMesh.numBoneInfluencers) {
  21285. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  21286. }
  21287. }
  21288. // Animations
  21289. if (parsedMesh.animations) {
  21290. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21291. var parsedAnimation = parsedMesh.animations[animationIndex];
  21292. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21293. }
  21294. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  21295. }
  21296. if (parsedMesh.autoAnimate) {
  21297. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  21298. }
  21299. // Layer Mask
  21300. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  21301. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  21302. }
  21303. else {
  21304. mesh.layerMask = 0x0FFFFFFF;
  21305. }
  21306. // Physics
  21307. if (parsedMesh.physicsImpostor) {
  21308. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  21309. mass: parsedMesh.physicsMass,
  21310. friction: parsedMesh.physicsFriction,
  21311. restitution: parsedMesh.physicsRestitution
  21312. }, scene);
  21313. }
  21314. // Instances
  21315. if (parsedMesh.instances) {
  21316. for (var index = 0; index < parsedMesh.instances.length; index++) {
  21317. var parsedInstance = parsedMesh.instances[index];
  21318. var instance = mesh.createInstance(parsedInstance.name);
  21319. if (BABYLON.Tags) {
  21320. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  21321. }
  21322. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  21323. if (parsedInstance.parentId) {
  21324. instance._waitingParentId = parsedInstance.parentId;
  21325. }
  21326. if (parsedInstance.rotationQuaternion) {
  21327. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  21328. }
  21329. else if (parsedInstance.rotation) {
  21330. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  21331. }
  21332. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  21333. instance.checkCollisions = mesh.checkCollisions;
  21334. if (parsedMesh.animations) {
  21335. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21336. parsedAnimation = parsedMesh.animations[animationIndex];
  21337. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21338. }
  21339. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  21340. }
  21341. }
  21342. }
  21343. return mesh;
  21344. };
  21345. /**
  21346. * Creates a ribbon mesh.
  21347. * Please consider using the same method from the MeshBuilder class instead.
  21348. * 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.
  21349. *
  21350. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21351. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21352. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21353. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21354. * 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.
  21355. * 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.
  21356. * 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
  21357. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21358. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21359. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21360. */
  21361. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  21362. return BABYLON.MeshBuilder.CreateRibbon(name, {
  21363. pathArray: pathArray,
  21364. closeArray: closeArray,
  21365. closePath: closePath,
  21366. offset: offset,
  21367. updatable: updatable,
  21368. sideOrientation: sideOrientation,
  21369. instance: instance
  21370. }, scene);
  21371. };
  21372. /**
  21373. * Creates a plane polygonal mesh. By default, this is a disc.
  21374. * Please consider using the same method from the MeshBuilder class instead.
  21375. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21376. * 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.
  21377. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21378. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21379. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21380. */
  21381. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  21382. var options = {
  21383. radius: radius,
  21384. tessellation: tessellation,
  21385. sideOrientation: sideOrientation,
  21386. updatable: updatable
  21387. };
  21388. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  21389. };
  21390. /**
  21391. * Creates a box mesh.
  21392. * Please consider using the same method from the MeshBuilder class instead.
  21393. * The parameter `size` sets the size (float) of each box side (default 1).
  21394. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21395. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21396. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21397. */
  21398. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  21399. var options = {
  21400. size: size,
  21401. sideOrientation: sideOrientation,
  21402. updatable: updatable
  21403. };
  21404. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  21405. };
  21406. /**
  21407. * Creates a sphere mesh.
  21408. * Please consider using the same method from the MeshBuilder class instead.
  21409. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  21410. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  21411. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21412. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21413. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21414. */
  21415. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  21416. var options = {
  21417. segments: segments,
  21418. diameterX: diameter,
  21419. diameterY: diameter,
  21420. diameterZ: diameter,
  21421. sideOrientation: sideOrientation,
  21422. updatable: updatable
  21423. };
  21424. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  21425. };
  21426. /**
  21427. * Creates a cylinder or a cone mesh.
  21428. * Please consider using the same method from the MeshBuilder class instead.
  21429. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21430. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21431. * 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.
  21432. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21433. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21434. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21435. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21436. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21437. */
  21438. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  21439. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  21440. if (scene !== undefined) {
  21441. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  21442. updatable = scene;
  21443. }
  21444. scene = subdivisions;
  21445. subdivisions = 1;
  21446. }
  21447. var options = {
  21448. height: height,
  21449. diameterTop: diameterTop,
  21450. diameterBottom: diameterBottom,
  21451. tessellation: tessellation,
  21452. subdivisions: subdivisions,
  21453. sideOrientation: sideOrientation,
  21454. updatable: updatable
  21455. };
  21456. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  21457. };
  21458. // Torus (Code from SharpDX.org)
  21459. /**
  21460. * Creates a torus mesh.
  21461. * Please consider using the same method from the MeshBuilder class instead.
  21462. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21463. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21464. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21465. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21466. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21467. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21468. */
  21469. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  21470. var options = {
  21471. diameter: diameter,
  21472. thickness: thickness,
  21473. tessellation: tessellation,
  21474. sideOrientation: sideOrientation,
  21475. updatable: updatable
  21476. };
  21477. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  21478. };
  21479. /**
  21480. * Creates a torus knot mesh.
  21481. * Please consider using the same method from the MeshBuilder class instead.
  21482. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21483. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21484. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21485. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21486. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21487. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21488. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21489. */
  21490. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  21491. var options = {
  21492. radius: radius,
  21493. tube: tube,
  21494. radialSegments: radialSegments,
  21495. tubularSegments: tubularSegments,
  21496. p: p,
  21497. q: q,
  21498. sideOrientation: sideOrientation,
  21499. updatable: updatable
  21500. };
  21501. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  21502. };
  21503. /**
  21504. * Creates a line mesh.
  21505. * Please consider using the same method from the MeshBuilder class instead.
  21506. * 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.
  21507. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21508. * The parameter `points` is an array successive Vector3.
  21509. * 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
  21510. * When updating an instance, remember that only point positions can change, not the number of points.
  21511. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21512. */
  21513. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  21514. var options = {
  21515. points: points,
  21516. updatable: updatable,
  21517. instance: instance
  21518. };
  21519. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  21520. };
  21521. /**
  21522. * Creates a dashed line mesh.
  21523. * Please consider using the same method from the MeshBuilder class instead.
  21524. * 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.
  21525. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21526. * The parameter `points` is an array successive Vector3.
  21527. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21528. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21529. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21530. * 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
  21531. * When updating an instance, remember that only point positions can change, not the number of points.
  21532. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21533. */
  21534. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  21535. var options = {
  21536. points: points,
  21537. dashSize: dashSize,
  21538. gapSize: gapSize,
  21539. dashNb: dashNb,
  21540. updatable: updatable,
  21541. instance: instance
  21542. };
  21543. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  21544. };
  21545. /**
  21546. * Creates a polygon mesh.
  21547. * Please consider using the same method from the MeshBuilder class instead.
  21548. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  21549. * 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.
  21550. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21551. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21552. * Remember you can only change the shape positions, not their number when updating a polygon.
  21553. */
  21554. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  21555. var options = {
  21556. shape: shape,
  21557. holes: holes,
  21558. updatable: updatable,
  21559. sideOrientation: sideOrientation
  21560. };
  21561. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  21562. };
  21563. /**
  21564. * Creates an extruded polygon mesh, with depth in the Y direction.
  21565. * Please consider using the same method from the MeshBuilder class instead.
  21566. */
  21567. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  21568. var options = {
  21569. shape: shape,
  21570. holes: holes,
  21571. depth: depth,
  21572. updatable: updatable,
  21573. sideOrientation: sideOrientation
  21574. };
  21575. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  21576. };
  21577. /**
  21578. * Creates an extruded shape mesh.
  21579. * 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.
  21580. * Please consider using the same method from the MeshBuilder class instead.
  21581. *
  21582. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21583. * 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
  21584. * extruded along the Z axis.
  21585. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21586. * 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.
  21587. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21588. * 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
  21589. * 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
  21590. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21591. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21592. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21593. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21594. */
  21595. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  21596. var options = {
  21597. shape: shape,
  21598. path: path,
  21599. scale: scale,
  21600. rotation: rotation,
  21601. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21602. sideOrientation: sideOrientation,
  21603. instance: instance,
  21604. updatable: updatable
  21605. };
  21606. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  21607. };
  21608. /**
  21609. * Creates an custom extruded shape mesh.
  21610. * 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.
  21611. * Please consider using the same method from the MeshBuilder class instead.
  21612. *
  21613. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21614. * 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
  21615. * extruded along the Z axis.
  21616. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21617. * 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
  21618. * and the distance of this point from the begining of the path :
  21619. * ```javascript
  21620. * var rotationFunction = function(i, distance) {
  21621. * // do things
  21622. * return rotationValue; }
  21623. * ```
  21624. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21625. * 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
  21626. * and the distance of this point from the begining of the path :
  21627. * ```javascript
  21628. * var scaleFunction = function(i, distance) {
  21629. * // do things
  21630. * return scaleValue;}
  21631. * ```
  21632. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21633. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21634. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21635. * 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
  21636. * 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
  21637. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21638. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21639. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21640. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21641. */
  21642. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  21643. var options = {
  21644. shape: shape,
  21645. path: path,
  21646. scaleFunction: scaleFunction,
  21647. rotationFunction: rotationFunction,
  21648. ribbonCloseArray: ribbonCloseArray,
  21649. ribbonClosePath: ribbonClosePath,
  21650. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21651. sideOrientation: sideOrientation,
  21652. instance: instance,
  21653. updatable: updatable
  21654. };
  21655. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  21656. };
  21657. /**
  21658. * Creates lathe mesh.
  21659. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  21660. * Please consider using the same method from the MeshBuilder class instead.
  21661. * 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
  21662. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  21663. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  21664. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  21665. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21666. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21667. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21668. */
  21669. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  21670. var options = {
  21671. shape: shape,
  21672. radius: radius,
  21673. tessellation: tessellation,
  21674. sideOrientation: sideOrientation,
  21675. updatable: updatable
  21676. };
  21677. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  21678. };
  21679. /**
  21680. * Creates a plane mesh.
  21681. * Please consider using the same method from the MeshBuilder class instead.
  21682. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  21683. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21684. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21685. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21686. */
  21687. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  21688. var options = {
  21689. size: size,
  21690. width: size,
  21691. height: size,
  21692. sideOrientation: sideOrientation,
  21693. updatable: updatable
  21694. };
  21695. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  21696. };
  21697. /**
  21698. * Creates a ground mesh.
  21699. * Please consider using the same method from the MeshBuilder class instead.
  21700. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  21701. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  21702. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21703. */
  21704. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  21705. var options = {
  21706. width: width,
  21707. height: height,
  21708. subdivisions: subdivisions,
  21709. updatable: updatable
  21710. };
  21711. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  21712. };
  21713. /**
  21714. * Creates a tiled ground mesh.
  21715. * Please consider using the same method from the MeshBuilder class instead.
  21716. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  21717. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  21718. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  21719. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  21720. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  21721. * numbers of subdivisions on the ground width and height of each tile.
  21722. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21723. */
  21724. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  21725. var options = {
  21726. xmin: xmin,
  21727. zmin: zmin,
  21728. xmax: xmax,
  21729. zmax: zmax,
  21730. subdivisions: subdivisions,
  21731. precision: precision,
  21732. updatable: updatable
  21733. };
  21734. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  21735. };
  21736. /**
  21737. * Creates a ground mesh from a height map.
  21738. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  21739. * Please consider using the same method from the MeshBuilder class instead.
  21740. * The parameter `url` sets the URL of the height map image resource.
  21741. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  21742. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  21743. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  21744. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  21745. * 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).
  21746. * This function is passed the newly built mesh :
  21747. * ```javascript
  21748. * function(mesh) { // do things
  21749. * return; }
  21750. * ```
  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.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  21754. var options = {
  21755. width: width,
  21756. height: height,
  21757. subdivisions: subdivisions,
  21758. minHeight: minHeight,
  21759. maxHeight: maxHeight,
  21760. updatable: updatable,
  21761. onReady: onReady
  21762. };
  21763. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  21764. };
  21765. /**
  21766. * Creates a tube mesh.
  21767. * 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.
  21768. * Please consider using the same method from the MeshBuilder class instead.
  21769. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21770. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21771. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21772. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21773. * 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.
  21774. * It must return a radius value (positive float) :
  21775. * ```javascript
  21776. * var radiusFunction = function(i, distance) {
  21777. * // do things
  21778. * return radius; }
  21779. * ```
  21780. * 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
  21781. * 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
  21782. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21783. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21784. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21785. */
  21786. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  21787. var options = {
  21788. path: path,
  21789. radius: radius,
  21790. tessellation: tessellation,
  21791. radiusFunction: radiusFunction,
  21792. arc: 1,
  21793. cap: cap,
  21794. updatable: updatable,
  21795. sideOrientation: sideOrientation,
  21796. instance: instance
  21797. };
  21798. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  21799. };
  21800. /**
  21801. * Creates a polyhedron mesh.
  21802. * Please consider using the same method from the MeshBuilder class instead.
  21803. * 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
  21804. * to choose the wanted type.
  21805. * The parameter `size` (positive float, default 1) sets the polygon size.
  21806. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  21807. * 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`.
  21808. * 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
  21809. * 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)`).
  21810. * 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
  21811. * 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.
  21812. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21813. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21814. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21815. */
  21816. Mesh.CreatePolyhedron = function (name, options, scene) {
  21817. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  21818. };
  21819. /**
  21820. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  21821. * Please consider using the same method from the MeshBuilder class instead.
  21822. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  21823. * 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`).
  21824. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  21825. * 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.
  21826. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21827. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21828. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21829. */
  21830. Mesh.CreateIcoSphere = function (name, options, scene) {
  21831. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  21832. };
  21833. /**
  21834. * Creates a decal mesh.
  21835. * Please consider using the same method from the MeshBuilder class instead.
  21836. * 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.
  21837. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  21838. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  21839. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  21840. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  21841. */
  21842. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  21843. var options = {
  21844. position: position,
  21845. normal: normal,
  21846. size: size,
  21847. angle: angle
  21848. };
  21849. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  21850. };
  21851. // Skeletons
  21852. /**
  21853. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21854. */
  21855. Mesh.prototype.setPositionsForCPUSkinning = function () {
  21856. var source;
  21857. if (!this._sourcePositions) {
  21858. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21859. this._sourcePositions = new Float32Array(source);
  21860. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  21861. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  21862. }
  21863. }
  21864. return this._sourcePositions;
  21865. };
  21866. /**
  21867. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21868. */
  21869. Mesh.prototype.setNormalsForCPUSkinning = function () {
  21870. var source;
  21871. if (!this._sourceNormals) {
  21872. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21873. this._sourceNormals = new Float32Array(source);
  21874. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  21875. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  21876. }
  21877. }
  21878. return this._sourceNormals;
  21879. };
  21880. /**
  21881. * Updates the vertex buffer by applying transformation from the bones.
  21882. * Returns the Mesh.
  21883. *
  21884. * @param {skeleton} skeleton to apply
  21885. */
  21886. Mesh.prototype.applySkeleton = function (skeleton) {
  21887. if (!this.geometry) {
  21888. return this;
  21889. }
  21890. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  21891. return this;
  21892. }
  21893. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  21894. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21895. return this;
  21896. }
  21897. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21898. return this;
  21899. }
  21900. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21901. return this;
  21902. }
  21903. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21904. return this;
  21905. }
  21906. if (!this._sourcePositions) {
  21907. var submeshes = this.subMeshes.slice();
  21908. this.setPositionsForCPUSkinning();
  21909. this.subMeshes = submeshes;
  21910. }
  21911. if (!this._sourceNormals) {
  21912. this.setNormalsForCPUSkinning();
  21913. }
  21914. // positionsData checks for not being Float32Array will only pass at most once
  21915. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21916. if (!(positionsData instanceof Float32Array)) {
  21917. positionsData = new Float32Array(positionsData);
  21918. }
  21919. // normalsData checks for not being Float32Array will only pass at most once
  21920. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21921. if (!(normalsData instanceof Float32Array)) {
  21922. normalsData = new Float32Array(normalsData);
  21923. }
  21924. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21925. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21926. var needExtras = this.numBoneInfluencers > 4;
  21927. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  21928. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  21929. var skeletonMatrices = skeleton.getTransformMatrices(this);
  21930. var tempVector3 = BABYLON.Vector3.Zero();
  21931. var finalMatrix = new BABYLON.Matrix();
  21932. var tempMatrix = new BABYLON.Matrix();
  21933. var matWeightIdx = 0;
  21934. var inf;
  21935. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  21936. var weight;
  21937. for (inf = 0; inf < 4; inf++) {
  21938. weight = matricesWeightsData[matWeightIdx + inf];
  21939. if (weight > 0) {
  21940. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21941. finalMatrix.addToSelf(tempMatrix);
  21942. }
  21943. else
  21944. break;
  21945. }
  21946. if (needExtras) {
  21947. for (inf = 0; inf < 4; inf++) {
  21948. weight = matricesWeightsExtraData[matWeightIdx + inf];
  21949. if (weight > 0) {
  21950. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21951. finalMatrix.addToSelf(tempMatrix);
  21952. }
  21953. else
  21954. break;
  21955. }
  21956. }
  21957. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  21958. tempVector3.toArray(positionsData, index);
  21959. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  21960. tempVector3.toArray(normalsData, index);
  21961. finalMatrix.reset();
  21962. }
  21963. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  21964. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  21965. return this;
  21966. };
  21967. // Tools
  21968. /**
  21969. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  21970. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  21971. */
  21972. Mesh.MinMax = function (meshes) {
  21973. var minVector = null;
  21974. var maxVector = null;
  21975. meshes.forEach(function (mesh, index, array) {
  21976. var boundingBox = mesh.getBoundingInfo().boundingBox;
  21977. if (!minVector) {
  21978. minVector = boundingBox.minimumWorld;
  21979. maxVector = boundingBox.maximumWorld;
  21980. }
  21981. else {
  21982. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  21983. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  21984. }
  21985. });
  21986. return {
  21987. min: minVector,
  21988. max: maxVector
  21989. };
  21990. };
  21991. /**
  21992. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  21993. */
  21994. Mesh.Center = function (meshesOrMinMaxVector) {
  21995. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  21996. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  21997. };
  21998. /**
  21999. * Merge the array of meshes into a single mesh for performance reasons.
  22000. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  22001. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  22002. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  22003. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  22004. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  22005. */
  22006. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  22007. if (disposeSource === void 0) { disposeSource = true; }
  22008. var index;
  22009. if (!allow32BitsIndices) {
  22010. var totalVertices = 0;
  22011. // Counting vertices
  22012. for (index = 0; index < meshes.length; index++) {
  22013. if (meshes[index]) {
  22014. totalVertices += meshes[index].getTotalVertices();
  22015. if (totalVertices > 65536) {
  22016. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  22017. return null;
  22018. }
  22019. }
  22020. }
  22021. }
  22022. // Merge
  22023. var vertexData;
  22024. var otherVertexData;
  22025. var indiceArray = new Array();
  22026. var source;
  22027. for (index = 0; index < meshes.length; index++) {
  22028. if (meshes[index]) {
  22029. meshes[index].computeWorldMatrix(true);
  22030. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  22031. otherVertexData.transform(meshes[index].getWorldMatrix());
  22032. if (vertexData) {
  22033. vertexData.merge(otherVertexData);
  22034. }
  22035. else {
  22036. vertexData = otherVertexData;
  22037. source = meshes[index];
  22038. }
  22039. if (subdivideWithSubMeshes) {
  22040. indiceArray.push(meshes[index].getTotalIndices());
  22041. }
  22042. }
  22043. }
  22044. if (!meshSubclass) {
  22045. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  22046. }
  22047. vertexData.applyToMesh(meshSubclass);
  22048. // Setting properties
  22049. meshSubclass.material = source.material;
  22050. meshSubclass.checkCollisions = source.checkCollisions;
  22051. // Cleaning
  22052. if (disposeSource) {
  22053. for (index = 0; index < meshes.length; index++) {
  22054. if (meshes[index]) {
  22055. meshes[index].dispose();
  22056. }
  22057. }
  22058. }
  22059. // Subdivide
  22060. if (subdivideWithSubMeshes) {
  22061. //-- Suppresions du submesh global
  22062. meshSubclass.releaseSubMeshes();
  22063. index = 0;
  22064. var offset = 0;
  22065. //-- aplique la subdivision en fonction du tableau d'indices
  22066. while (index < indiceArray.length) {
  22067. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  22068. offset += indiceArray[index];
  22069. index++;
  22070. }
  22071. }
  22072. return meshSubclass;
  22073. };
  22074. return Mesh;
  22075. }(BABYLON.AbstractMesh));
  22076. // Consts
  22077. Mesh._FRONTSIDE = 0;
  22078. Mesh._BACKSIDE = 1;
  22079. Mesh._DOUBLESIDE = 2;
  22080. Mesh._DEFAULTSIDE = 0;
  22081. Mesh._NO_CAP = 0;
  22082. Mesh._CAP_START = 1;
  22083. Mesh._CAP_END = 2;
  22084. Mesh._CAP_ALL = 3;
  22085. BABYLON.Mesh = Mesh;
  22086. })(BABYLON || (BABYLON = {}));
  22087. //# sourceMappingURL=babylon.mesh.js.map
  22088. var BABYLON;
  22089. (function (BABYLON) {
  22090. var SubMesh = (function () {
  22091. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  22092. if (createBoundingBox === void 0) { createBoundingBox = true; }
  22093. this.materialIndex = materialIndex;
  22094. this.verticesStart = verticesStart;
  22095. this.verticesCount = verticesCount;
  22096. this.indexStart = indexStart;
  22097. this.indexCount = indexCount;
  22098. this._renderId = 0;
  22099. this._mesh = mesh;
  22100. this._renderingMesh = renderingMesh || mesh;
  22101. mesh.subMeshes.push(this);
  22102. this._trianglePlanes = [];
  22103. this._id = mesh.subMeshes.length - 1;
  22104. if (createBoundingBox) {
  22105. this.refreshBoundingInfo();
  22106. mesh.computeWorldMatrix(true);
  22107. }
  22108. }
  22109. Object.defineProperty(SubMesh.prototype, "effect", {
  22110. get: function () {
  22111. return this._materialEffect;
  22112. },
  22113. enumerable: true,
  22114. configurable: true
  22115. });
  22116. SubMesh.prototype.setEffect = function (effect, defines) {
  22117. if (this._materialEffect === effect) {
  22118. return;
  22119. }
  22120. this._materialDefines = defines;
  22121. this._materialEffect = effect;
  22122. };
  22123. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  22124. get: function () {
  22125. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  22126. },
  22127. enumerable: true,
  22128. configurable: true
  22129. });
  22130. /**
  22131. * Returns the submesh BoudingInfo object.
  22132. */
  22133. SubMesh.prototype.getBoundingInfo = function () {
  22134. if (this.IsGlobal) {
  22135. return this._mesh.getBoundingInfo();
  22136. }
  22137. return this._boundingInfo;
  22138. };
  22139. /**
  22140. * Sets the submesh BoundingInfo.
  22141. * Return the SubMesh.
  22142. */
  22143. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  22144. this._boundingInfo = boundingInfo;
  22145. return this;
  22146. };
  22147. /**
  22148. * Returns the mesh of the current submesh.
  22149. */
  22150. SubMesh.prototype.getMesh = function () {
  22151. return this._mesh;
  22152. };
  22153. /**
  22154. * Returns the rendering mesh of the submesh.
  22155. */
  22156. SubMesh.prototype.getRenderingMesh = function () {
  22157. return this._renderingMesh;
  22158. };
  22159. /**
  22160. * Returns the submesh material.
  22161. */
  22162. SubMesh.prototype.getMaterial = function () {
  22163. var rootMaterial = this._renderingMesh.material;
  22164. if (rootMaterial && rootMaterial.getSubMaterial) {
  22165. var multiMaterial = rootMaterial;
  22166. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  22167. if (this._currentMaterial !== effectiveMaterial) {
  22168. this._currentMaterial = effectiveMaterial;
  22169. if (this._materialDefines) {
  22170. this._materialDefines.markAllAsDirty();
  22171. }
  22172. }
  22173. return effectiveMaterial;
  22174. }
  22175. if (!rootMaterial) {
  22176. return this._mesh.getScene().defaultMaterial;
  22177. }
  22178. return rootMaterial;
  22179. };
  22180. // Methods
  22181. /**
  22182. * Sets a new updated BoundingInfo object to the submesh.
  22183. * Returns the SubMesh.
  22184. */
  22185. SubMesh.prototype.refreshBoundingInfo = function () {
  22186. this._lastColliderWorldVertices = null;
  22187. if (this.IsGlobal) {
  22188. return;
  22189. }
  22190. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22191. if (!data) {
  22192. this._boundingInfo = this._mesh._boundingInfo;
  22193. return;
  22194. }
  22195. var indices = this._renderingMesh.getIndices();
  22196. var extend;
  22197. //is this the only submesh?
  22198. if (this.indexStart === 0 && this.indexCount === indices.length) {
  22199. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  22200. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  22201. }
  22202. else {
  22203. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  22204. }
  22205. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22206. return this;
  22207. };
  22208. SubMesh.prototype._checkCollision = function (collider) {
  22209. return this.getBoundingInfo()._checkCollision(collider);
  22210. };
  22211. /**
  22212. * Updates the submesh BoundingInfo.
  22213. * Returns the Submesh.
  22214. */
  22215. SubMesh.prototype.updateBoundingInfo = function (world) {
  22216. if (!this.getBoundingInfo()) {
  22217. this.refreshBoundingInfo();
  22218. }
  22219. this.getBoundingInfo().update(world);
  22220. return this;
  22221. };
  22222. /**
  22223. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  22224. * Boolean returned.
  22225. */
  22226. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  22227. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  22228. };
  22229. /**
  22230. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  22231. * Boolean returned.
  22232. */
  22233. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  22234. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  22235. };
  22236. /**
  22237. * Renders the submesh.
  22238. * Returns it.
  22239. */
  22240. SubMesh.prototype.render = function (enableAlphaMode) {
  22241. this._renderingMesh.render(this, enableAlphaMode);
  22242. return this;
  22243. };
  22244. /**
  22245. * Returns a new Index Buffer.
  22246. * Type returned : WebGLBuffer.
  22247. */
  22248. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  22249. if (!this._linesIndexBuffer) {
  22250. var linesIndices = [];
  22251. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22252. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  22253. }
  22254. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  22255. this.linesIndexCount = linesIndices.length;
  22256. }
  22257. return this._linesIndexBuffer;
  22258. };
  22259. /**
  22260. * True is the passed Ray intersects the submesh bounding box.
  22261. * Boolean returned.
  22262. */
  22263. SubMesh.prototype.canIntersects = function (ray) {
  22264. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  22265. };
  22266. /**
  22267. * Returns an object IntersectionInfo.
  22268. */
  22269. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  22270. var intersectInfo = null;
  22271. // LineMesh first as it's also a Mesh...
  22272. if (this._mesh instanceof BABYLON.LinesMesh) {
  22273. var lineMesh = this._mesh;
  22274. // Line test
  22275. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  22276. var p0 = positions[indices[index]];
  22277. var p1 = positions[indices[index + 1]];
  22278. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  22279. if (length < 0) {
  22280. continue;
  22281. }
  22282. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  22283. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  22284. if (fastCheck) {
  22285. break;
  22286. }
  22287. }
  22288. }
  22289. }
  22290. else {
  22291. // Triangles test
  22292. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22293. var p0 = positions[indices[index]];
  22294. var p1 = positions[indices[index + 1]];
  22295. var p2 = positions[indices[index + 2]];
  22296. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  22297. if (currentIntersectInfo) {
  22298. if (currentIntersectInfo.distance < 0) {
  22299. continue;
  22300. }
  22301. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  22302. intersectInfo = currentIntersectInfo;
  22303. intersectInfo.faceId = index / 3;
  22304. if (fastCheck) {
  22305. break;
  22306. }
  22307. }
  22308. }
  22309. }
  22310. }
  22311. return intersectInfo;
  22312. };
  22313. // Clone
  22314. /**
  22315. * Creates a new Submesh from the passed Mesh.
  22316. */
  22317. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  22318. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  22319. if (!this.IsGlobal) {
  22320. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  22321. }
  22322. return result;
  22323. };
  22324. // Dispose
  22325. /**
  22326. * Disposes the Submesh.
  22327. * Returns nothing.
  22328. */
  22329. SubMesh.prototype.dispose = function () {
  22330. if (this._linesIndexBuffer) {
  22331. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  22332. this._linesIndexBuffer = null;
  22333. }
  22334. // Remove from mesh
  22335. var index = this._mesh.subMeshes.indexOf(this);
  22336. this._mesh.subMeshes.splice(index, 1);
  22337. };
  22338. // Statics
  22339. /**
  22340. * Creates a new Submesh from the passed parameters :
  22341. * - materialIndex (integer) : the index of the main mesh material.
  22342. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  22343. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  22344. * - mesh (Mesh) : the main mesh to create the submesh from.
  22345. * - renderingMesh (optional Mesh) : rendering mesh.
  22346. */
  22347. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  22348. var minVertexIndex = Number.MAX_VALUE;
  22349. var maxVertexIndex = -Number.MAX_VALUE;
  22350. renderingMesh = renderingMesh || mesh;
  22351. var indices = renderingMesh.getIndices();
  22352. for (var index = startIndex; index < startIndex + indexCount; index++) {
  22353. var vertexIndex = indices[index];
  22354. if (vertexIndex < minVertexIndex)
  22355. minVertexIndex = vertexIndex;
  22356. if (vertexIndex > maxVertexIndex)
  22357. maxVertexIndex = vertexIndex;
  22358. }
  22359. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  22360. };
  22361. return SubMesh;
  22362. }());
  22363. BABYLON.SubMesh = SubMesh;
  22364. })(BABYLON || (BABYLON = {}));
  22365. //# sourceMappingURL=babylon.subMesh.js.map
  22366. var BABYLON;
  22367. (function (BABYLON) {
  22368. var EffectFallbacks = (function () {
  22369. function EffectFallbacks() {
  22370. this._defines = {};
  22371. this._currentRank = 32;
  22372. this._maxRank = -1;
  22373. }
  22374. EffectFallbacks.prototype.addFallback = function (rank, define) {
  22375. if (!this._defines[rank]) {
  22376. if (rank < this._currentRank) {
  22377. this._currentRank = rank;
  22378. }
  22379. if (rank > this._maxRank) {
  22380. this._maxRank = rank;
  22381. }
  22382. this._defines[rank] = new Array();
  22383. }
  22384. this._defines[rank].push(define);
  22385. };
  22386. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  22387. this._meshRank = rank;
  22388. this._mesh = mesh;
  22389. if (rank < this._currentRank) {
  22390. this._currentRank = rank;
  22391. }
  22392. if (rank > this._maxRank) {
  22393. this._maxRank = rank;
  22394. }
  22395. };
  22396. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  22397. get: function () {
  22398. return this._currentRank <= this._maxRank;
  22399. },
  22400. enumerable: true,
  22401. configurable: true
  22402. });
  22403. EffectFallbacks.prototype.reduce = function (currentDefines) {
  22404. // First we try to switch to CPU skinning
  22405. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  22406. this._mesh.computeBonesUsingShaders = false;
  22407. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  22408. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  22409. var scene = this._mesh.getScene();
  22410. for (var index = 0; index < scene.meshes.length; index++) {
  22411. var otherMesh = scene.meshes[index];
  22412. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  22413. otherMesh.computeBonesUsingShaders = false;
  22414. }
  22415. }
  22416. }
  22417. else {
  22418. var currentFallbacks = this._defines[this._currentRank];
  22419. if (currentFallbacks) {
  22420. for (var index = 0; index < currentFallbacks.length; index++) {
  22421. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  22422. }
  22423. }
  22424. this._currentRank++;
  22425. }
  22426. return currentDefines;
  22427. };
  22428. return EffectFallbacks;
  22429. }());
  22430. BABYLON.EffectFallbacks = EffectFallbacks;
  22431. var EffectCreationOptions = (function () {
  22432. function EffectCreationOptions() {
  22433. }
  22434. return EffectCreationOptions;
  22435. }());
  22436. BABYLON.EffectCreationOptions = EffectCreationOptions;
  22437. var Effect = (function () {
  22438. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  22439. var _this = this;
  22440. this.uniqueId = 0;
  22441. this._uniformBuffersNames = {};
  22442. this._isReady = false;
  22443. this._compilationError = "";
  22444. this._valueCache = {};
  22445. this.name = baseName;
  22446. if (attributesNamesOrOptions.attributes) {
  22447. var options = attributesNamesOrOptions;
  22448. this._engine = uniformsNamesOrEngine;
  22449. this._attributesNames = options.attributes;
  22450. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  22451. this._samplers = options.samplers;
  22452. this.defines = options.defines;
  22453. this.onError = options.onError;
  22454. this.onCompiled = options.onCompiled;
  22455. this._fallbacks = options.fallbacks;
  22456. this._indexParameters = options.indexParameters;
  22457. if (options.uniformBuffersNames) {
  22458. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  22459. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  22460. }
  22461. }
  22462. }
  22463. else {
  22464. this._engine = engine;
  22465. this.defines = defines;
  22466. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  22467. this._samplers = samplers;
  22468. this._attributesNames = attributesNamesOrOptions;
  22469. this.onError = onError;
  22470. this.onCompiled = onCompiled;
  22471. this._indexParameters = indexParameters;
  22472. this._fallbacks = fallbacks;
  22473. }
  22474. this.uniqueId = Effect._uniqueIdSeed++;
  22475. var vertexSource;
  22476. var fragmentSource;
  22477. if (baseName.vertexElement) {
  22478. vertexSource = document.getElementById(baseName.vertexElement);
  22479. if (!vertexSource) {
  22480. vertexSource = baseName.vertexElement;
  22481. }
  22482. }
  22483. else {
  22484. vertexSource = baseName.vertex || baseName;
  22485. }
  22486. if (baseName.fragmentElement) {
  22487. fragmentSource = document.getElementById(baseName.fragmentElement);
  22488. if (!fragmentSource) {
  22489. fragmentSource = baseName.fragmentElement;
  22490. }
  22491. }
  22492. else {
  22493. fragmentSource = baseName.fragment || baseName;
  22494. }
  22495. this._loadVertexShader(vertexSource, function (vertexCode) {
  22496. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  22497. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  22498. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  22499. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  22500. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  22501. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, _this._attributesNames, _this.defines, _this._fallbacks);
  22502. });
  22503. });
  22504. });
  22505. });
  22506. });
  22507. });
  22508. }
  22509. Object.defineProperty(Effect.prototype, "key", {
  22510. get: function () {
  22511. return this._key;
  22512. },
  22513. enumerable: true,
  22514. configurable: true
  22515. });
  22516. // Properties
  22517. Effect.prototype.isReady = function () {
  22518. return this._isReady;
  22519. };
  22520. Effect.prototype.getProgram = function () {
  22521. return this._program;
  22522. };
  22523. Effect.prototype.getAttributesNames = function () {
  22524. return this._attributesNames;
  22525. };
  22526. Effect.prototype.getAttributeLocation = function (index) {
  22527. return this._attributes[index];
  22528. };
  22529. Effect.prototype.getAttributeLocationByName = function (name) {
  22530. var index = this._attributesNames.indexOf(name);
  22531. return this._attributes[index];
  22532. };
  22533. Effect.prototype.getAttributesCount = function () {
  22534. return this._attributes.length;
  22535. };
  22536. Effect.prototype.getUniformIndex = function (uniformName) {
  22537. return this._uniformsNames.indexOf(uniformName);
  22538. };
  22539. Effect.prototype.getUniform = function (uniformName) {
  22540. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  22541. };
  22542. Effect.prototype.getSamplers = function () {
  22543. return this._samplers;
  22544. };
  22545. Effect.prototype.getCompilationError = function () {
  22546. return this._compilationError;
  22547. };
  22548. Effect.prototype.getVertexShaderSource = function () {
  22549. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  22550. };
  22551. Effect.prototype.getFragmentShaderSource = function () {
  22552. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  22553. };
  22554. // Methods
  22555. Effect.prototype._loadVertexShader = function (vertex, callback) {
  22556. // DOM element ?
  22557. if (vertex instanceof HTMLElement) {
  22558. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  22559. callback(vertexCode);
  22560. return;
  22561. }
  22562. // Base64 encoded ?
  22563. if (vertex.substr(0, 7) === "base64:") {
  22564. var vertexBinary = window.atob(vertex.substr(7));
  22565. callback(vertexBinary);
  22566. return;
  22567. }
  22568. // Is in local store ?
  22569. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  22570. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  22571. return;
  22572. }
  22573. var vertexShaderUrl;
  22574. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  22575. vertexShaderUrl = vertex;
  22576. }
  22577. else {
  22578. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  22579. }
  22580. // Vertex shader
  22581. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  22582. };
  22583. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  22584. // DOM element ?
  22585. if (fragment instanceof HTMLElement) {
  22586. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  22587. callback(fragmentCode);
  22588. return;
  22589. }
  22590. // Base64 encoded ?
  22591. if (fragment.substr(0, 7) === "base64:") {
  22592. var fragmentBinary = window.atob(fragment.substr(7));
  22593. callback(fragmentBinary);
  22594. return;
  22595. }
  22596. // Is in local store ?
  22597. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  22598. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  22599. return;
  22600. }
  22601. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  22602. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  22603. return;
  22604. }
  22605. var fragmentShaderUrl;
  22606. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  22607. fragmentShaderUrl = fragment;
  22608. }
  22609. else {
  22610. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  22611. }
  22612. // Fragment shader
  22613. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  22614. };
  22615. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  22616. // Rebuild shaders source code
  22617. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  22618. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  22619. vertexCode = prefix + vertexCode;
  22620. fragmentCode = prefix + fragmentCode;
  22621. // Number lines of shaders source code
  22622. var i = 2;
  22623. var regex = /\n/gm;
  22624. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  22625. i = 2;
  22626. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  22627. // Dump shaders name and formatted source code
  22628. if (this.name.vertexElement) {
  22629. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  22630. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  22631. }
  22632. else if (this.name.vertex) {
  22633. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  22634. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  22635. }
  22636. else {
  22637. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  22638. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  22639. }
  22640. };
  22641. ;
  22642. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  22643. var preparedSourceCode = this._processPrecision(sourceCode);
  22644. if (this._engine.webGLVersion == 1) {
  22645. callback(preparedSourceCode);
  22646. return;
  22647. }
  22648. // Already converted
  22649. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  22650. callback(preparedSourceCode.replace("#version 300 es", ""));
  22651. return;
  22652. }
  22653. // Remove extensions
  22654. // #extension GL_OES_standard_derivatives : enable
  22655. // #extension GL_EXT_shader_texture_lod : enable
  22656. // #extension GL_EXT_frag_depth : enable
  22657. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  22658. var result = preparedSourceCode.replace(regex, "");
  22659. // Migrate to GLSL v300
  22660. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  22661. result = result.replace(/attribute[ \t]/g, "in ");
  22662. result = result.replace(/[ \t]attribute/g, " in");
  22663. if (isFragment) {
  22664. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  22665. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  22666. result = result.replace(/texture2D\(/g, "texture(");
  22667. result = result.replace(/textureCube\(/g, "texture(");
  22668. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  22669. result = result.replace(/gl_FragColor/g, "glFragColor");
  22670. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  22671. }
  22672. callback(result);
  22673. };
  22674. Effect.prototype._processIncludes = function (sourceCode, callback) {
  22675. var _this = this;
  22676. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  22677. var match = regex.exec(sourceCode);
  22678. var returnValue = new String(sourceCode);
  22679. while (match != null) {
  22680. var includeFile = match[1];
  22681. // Uniform declaration
  22682. if (includeFile.indexOf("__decl__") !== -1) {
  22683. includeFile = includeFile.replace(/__decl__/, "");
  22684. if (this._engine.webGLVersion != 1) {
  22685. includeFile = includeFile.replace(/Vertex/, "Ubo");
  22686. includeFile = includeFile.replace(/Fragment/, "Ubo");
  22687. }
  22688. includeFile = includeFile + "Declaration";
  22689. }
  22690. if (Effect.IncludesShadersStore[includeFile]) {
  22691. // Substitution
  22692. var includeContent = Effect.IncludesShadersStore[includeFile];
  22693. if (match[2]) {
  22694. var splits = match[3].split(",");
  22695. for (var index = 0; index < splits.length; index += 2) {
  22696. var source = new RegExp(splits[index], "g");
  22697. var dest = splits[index + 1];
  22698. includeContent = includeContent.replace(source, dest);
  22699. }
  22700. }
  22701. if (match[4]) {
  22702. var indexString = match[5];
  22703. if (indexString.indexOf("..") !== -1) {
  22704. var indexSplits = indexString.split("..");
  22705. var minIndex = parseInt(indexSplits[0]);
  22706. var maxIndex = parseInt(indexSplits[1]);
  22707. var sourceIncludeContent = includeContent.slice(0);
  22708. includeContent = "";
  22709. if (isNaN(maxIndex)) {
  22710. maxIndex = this._indexParameters[indexSplits[1]];
  22711. }
  22712. for (var i = minIndex; i < maxIndex; i++) {
  22713. if (this._engine.webGLVersion === 1) {
  22714. // Ubo replacement
  22715. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  22716. return p1 + "{X}";
  22717. });
  22718. }
  22719. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  22720. }
  22721. }
  22722. else {
  22723. if (this._engine.webGLVersion === 1) {
  22724. // Ubo replacement
  22725. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  22726. return p1 + "{X}";
  22727. });
  22728. }
  22729. includeContent = includeContent.replace(/\{X\}/g, indexString);
  22730. }
  22731. }
  22732. // Replace
  22733. returnValue = returnValue.replace(match[0], includeContent);
  22734. }
  22735. else {
  22736. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  22737. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  22738. Effect.IncludesShadersStore[includeFile] = fileContent;
  22739. _this._processIncludes(returnValue, callback);
  22740. });
  22741. return;
  22742. }
  22743. match = regex.exec(sourceCode);
  22744. }
  22745. callback(returnValue);
  22746. };
  22747. Effect.prototype._processPrecision = function (source) {
  22748. if (source.indexOf("precision highp float") === -1) {
  22749. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  22750. source = "precision mediump float;\n" + source;
  22751. }
  22752. else {
  22753. source = "precision highp float;\n" + source;
  22754. }
  22755. }
  22756. else {
  22757. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  22758. source = source.replace("precision highp float", "precision mediump float");
  22759. }
  22760. }
  22761. return source;
  22762. };
  22763. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  22764. try {
  22765. var engine = this._engine;
  22766. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  22767. if (engine.webGLVersion > 1) {
  22768. for (var name in this._uniformBuffersNames) {
  22769. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  22770. }
  22771. }
  22772. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  22773. this._attributes = engine.getAttributes(this._program, attributesNames);
  22774. var index;
  22775. for (index = 0; index < this._samplers.length; index++) {
  22776. var sampler = this.getUniform(this._samplers[index]);
  22777. if (sampler == null) {
  22778. this._samplers.splice(index, 1);
  22779. index--;
  22780. }
  22781. }
  22782. engine.bindSamplers(this);
  22783. this._compilationError = "";
  22784. this._isReady = true;
  22785. if (this.onCompiled) {
  22786. this.onCompiled(this);
  22787. }
  22788. }
  22789. catch (e) {
  22790. this._compilationError = e.message;
  22791. // Let's go through fallbacks then
  22792. BABYLON.Tools.Error("Unable to compile effect:");
  22793. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  22794. return " " + uniform;
  22795. }));
  22796. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  22797. return " " + attribute;
  22798. }));
  22799. this._dumpShadersSource(vertexSourceCode, fragmentSourceCode, defines);
  22800. BABYLON.Tools.Error("Error: " + this._compilationError);
  22801. if (fallbacks && fallbacks.isMoreFallbacks) {
  22802. BABYLON.Tools.Error("Trying next fallback.");
  22803. defines = fallbacks.reduce(defines);
  22804. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  22805. }
  22806. else {
  22807. if (this.onError) {
  22808. this.onError(this, this._compilationError);
  22809. }
  22810. }
  22811. }
  22812. };
  22813. Object.defineProperty(Effect.prototype, "isSupported", {
  22814. get: function () {
  22815. return this._compilationError === "";
  22816. },
  22817. enumerable: true,
  22818. configurable: true
  22819. });
  22820. Effect.prototype._bindTexture = function (channel, texture) {
  22821. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  22822. };
  22823. Effect.prototype.setTexture = function (channel, texture) {
  22824. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  22825. };
  22826. Effect.prototype.setTextureArray = function (channel, textures) {
  22827. if (this._samplers.indexOf(channel + "Ex") === -1) {
  22828. var initialPos = this._samplers.indexOf(channel);
  22829. for (var index = 1; index < textures.length; index++) {
  22830. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  22831. }
  22832. }
  22833. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  22834. };
  22835. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  22836. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  22837. };
  22838. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  22839. var cache = this._valueCache[uniformName];
  22840. var flag = matrix.updateFlag;
  22841. if (cache !== undefined && cache === flag) {
  22842. return false;
  22843. }
  22844. this._valueCache[uniformName] = flag;
  22845. return true;
  22846. };
  22847. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  22848. var cache = this._valueCache[uniformName];
  22849. if (!cache) {
  22850. cache = [x, y];
  22851. this._valueCache[uniformName] = cache;
  22852. return true;
  22853. }
  22854. var changed = false;
  22855. if (cache[0] !== x) {
  22856. cache[0] = x;
  22857. changed = true;
  22858. }
  22859. if (cache[1] !== y) {
  22860. cache[1] = y;
  22861. changed = true;
  22862. }
  22863. return changed;
  22864. };
  22865. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  22866. var cache = this._valueCache[uniformName];
  22867. if (!cache) {
  22868. cache = [x, y, z];
  22869. this._valueCache[uniformName] = cache;
  22870. return true;
  22871. }
  22872. var changed = false;
  22873. if (cache[0] !== x) {
  22874. cache[0] = x;
  22875. changed = true;
  22876. }
  22877. if (cache[1] !== y) {
  22878. cache[1] = y;
  22879. changed = true;
  22880. }
  22881. if (cache[2] !== z) {
  22882. cache[2] = z;
  22883. changed = true;
  22884. }
  22885. return changed;
  22886. };
  22887. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  22888. var cache = this._valueCache[uniformName];
  22889. if (!cache) {
  22890. cache = [x, y, z, w];
  22891. this._valueCache[uniformName] = cache;
  22892. return true;
  22893. }
  22894. var changed = false;
  22895. if (cache[0] !== x) {
  22896. cache[0] = x;
  22897. changed = true;
  22898. }
  22899. if (cache[1] !== y) {
  22900. cache[1] = y;
  22901. changed = true;
  22902. }
  22903. if (cache[2] !== z) {
  22904. cache[2] = z;
  22905. changed = true;
  22906. }
  22907. if (cache[3] !== w) {
  22908. cache[3] = w;
  22909. changed = true;
  22910. }
  22911. return changed;
  22912. };
  22913. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  22914. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  22915. return;
  22916. }
  22917. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  22918. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  22919. };
  22920. Effect.prototype.bindUniformBlock = function (blockName, index) {
  22921. this._engine.bindUniformBlock(this._program, blockName, index);
  22922. };
  22923. Effect.prototype.setIntArray = function (uniformName, array) {
  22924. this._valueCache[uniformName] = null;
  22925. this._engine.setIntArray(this.getUniform(uniformName), array);
  22926. return this;
  22927. };
  22928. Effect.prototype.setIntArray2 = function (uniformName, array) {
  22929. this._valueCache[uniformName] = null;
  22930. this._engine.setIntArray2(this.getUniform(uniformName), array);
  22931. return this;
  22932. };
  22933. Effect.prototype.setIntArray3 = function (uniformName, array) {
  22934. this._valueCache[uniformName] = null;
  22935. this._engine.setIntArray3(this.getUniform(uniformName), array);
  22936. return this;
  22937. };
  22938. Effect.prototype.setIntArray4 = function (uniformName, array) {
  22939. this._valueCache[uniformName] = null;
  22940. this._engine.setIntArray4(this.getUniform(uniformName), array);
  22941. return this;
  22942. };
  22943. Effect.prototype.setFloatArray = function (uniformName, array) {
  22944. this._valueCache[uniformName] = null;
  22945. this._engine.setFloatArray(this.getUniform(uniformName), array);
  22946. return this;
  22947. };
  22948. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  22949. this._valueCache[uniformName] = null;
  22950. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  22951. return this;
  22952. };
  22953. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  22954. this._valueCache[uniformName] = null;
  22955. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  22956. return this;
  22957. };
  22958. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  22959. this._valueCache[uniformName] = null;
  22960. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  22961. return this;
  22962. };
  22963. Effect.prototype.setArray = function (uniformName, array) {
  22964. this._valueCache[uniformName] = null;
  22965. this._engine.setArray(this.getUniform(uniformName), array);
  22966. return this;
  22967. };
  22968. Effect.prototype.setArray2 = function (uniformName, array) {
  22969. this._valueCache[uniformName] = null;
  22970. this._engine.setArray2(this.getUniform(uniformName), array);
  22971. return this;
  22972. };
  22973. Effect.prototype.setArray3 = function (uniformName, array) {
  22974. this._valueCache[uniformName] = null;
  22975. this._engine.setArray3(this.getUniform(uniformName), array);
  22976. return this;
  22977. };
  22978. Effect.prototype.setArray4 = function (uniformName, array) {
  22979. this._valueCache[uniformName] = null;
  22980. this._engine.setArray4(this.getUniform(uniformName), array);
  22981. return this;
  22982. };
  22983. Effect.prototype.setMatrices = function (uniformName, matrices) {
  22984. if (!matrices) {
  22985. return;
  22986. }
  22987. this._valueCache[uniformName] = null;
  22988. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  22989. return this;
  22990. };
  22991. Effect.prototype.setMatrix = function (uniformName, matrix) {
  22992. if (this._cacheMatrix(uniformName, matrix)) {
  22993. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  22994. }
  22995. return this;
  22996. };
  22997. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  22998. this._valueCache[uniformName] = null;
  22999. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  23000. return this;
  23001. };
  23002. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  23003. this._valueCache[uniformName] = null;
  23004. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  23005. return this;
  23006. };
  23007. Effect.prototype.setFloat = function (uniformName, value) {
  23008. var cache = this._valueCache[uniformName];
  23009. if (cache !== undefined && cache === value)
  23010. return this;
  23011. this._valueCache[uniformName] = value;
  23012. this._engine.setFloat(this.getUniform(uniformName), value);
  23013. return this;
  23014. };
  23015. Effect.prototype.setBool = function (uniformName, bool) {
  23016. var cache = this._valueCache[uniformName];
  23017. if (cache !== undefined && cache === bool)
  23018. return this;
  23019. this._valueCache[uniformName] = bool;
  23020. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  23021. return this;
  23022. };
  23023. Effect.prototype.setVector2 = function (uniformName, vector2) {
  23024. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  23025. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  23026. }
  23027. return this;
  23028. };
  23029. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  23030. if (this._cacheFloat2(uniformName, x, y)) {
  23031. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  23032. }
  23033. return this;
  23034. };
  23035. Effect.prototype.setVector3 = function (uniformName, vector3) {
  23036. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  23037. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  23038. }
  23039. return this;
  23040. };
  23041. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  23042. if (this._cacheFloat3(uniformName, x, y, z)) {
  23043. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  23044. }
  23045. return this;
  23046. };
  23047. Effect.prototype.setVector4 = function (uniformName, vector4) {
  23048. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  23049. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  23050. }
  23051. return this;
  23052. };
  23053. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  23054. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  23055. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  23056. }
  23057. return this;
  23058. };
  23059. Effect.prototype.setColor3 = function (uniformName, color3) {
  23060. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  23061. this._engine.setColor3(this.getUniform(uniformName), color3);
  23062. }
  23063. return this;
  23064. };
  23065. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  23066. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  23067. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  23068. }
  23069. return this;
  23070. };
  23071. Effect.prototype._recombineShader = function (node) {
  23072. if (node.define) {
  23073. if (node.condition) {
  23074. var defineIndex = this.defines.indexOf("#define " + node.define);
  23075. if (defineIndex === -1) {
  23076. return null;
  23077. }
  23078. var nextComma = this.defines.indexOf("\n", defineIndex);
  23079. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  23080. var condition = defineValue + node.condition;
  23081. if (!eval(condition)) {
  23082. return null;
  23083. }
  23084. }
  23085. else if (node.ndef) {
  23086. if (this.defines.indexOf("#define " + node.define) !== -1) {
  23087. return null;
  23088. }
  23089. }
  23090. else if (this.defines.indexOf("#define " + node.define) === -1) {
  23091. return null;
  23092. }
  23093. }
  23094. var result = "";
  23095. for (var index = 0; index < node.children.length; index++) {
  23096. var line = node.children[index];
  23097. if (line.children) {
  23098. var combined = this._recombineShader(line);
  23099. if (combined !== null) {
  23100. result += combined + "\r\n";
  23101. }
  23102. continue;
  23103. }
  23104. if (line.length > 0) {
  23105. result += line + "\r\n";
  23106. }
  23107. }
  23108. return result;
  23109. };
  23110. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  23111. var root = {
  23112. children: []
  23113. };
  23114. var currentNode = root;
  23115. var lines = shaderString.split("\n");
  23116. for (var index = 0; index < lines.length; index++) {
  23117. var line = lines[index].trim();
  23118. // #ifdef
  23119. var pos = line.indexOf("#ifdef ");
  23120. if (pos !== -1) {
  23121. var define = line.substr(pos + 7);
  23122. var newNode = {
  23123. condition: null,
  23124. ndef: false,
  23125. define: define,
  23126. children: [],
  23127. parent: currentNode
  23128. };
  23129. currentNode.children.push(newNode);
  23130. currentNode = newNode;
  23131. continue;
  23132. }
  23133. // #ifndef
  23134. var pos = line.indexOf("#ifndef ");
  23135. if (pos !== -1) {
  23136. var define = line.substr(pos + 8);
  23137. newNode = {
  23138. condition: null,
  23139. define: define,
  23140. ndef: true,
  23141. children: [],
  23142. parent: currentNode
  23143. };
  23144. currentNode.children.push(newNode);
  23145. currentNode = newNode;
  23146. continue;
  23147. }
  23148. // #if
  23149. var pos = line.indexOf("#if ");
  23150. if (pos !== -1) {
  23151. var define = line.substr(pos + 4).trim();
  23152. var conditionPos = define.indexOf(" ");
  23153. newNode = {
  23154. condition: define.substr(conditionPos + 1),
  23155. define: define.substr(0, conditionPos),
  23156. ndef: false,
  23157. children: [],
  23158. parent: currentNode
  23159. };
  23160. currentNode.children.push(newNode);
  23161. currentNode = newNode;
  23162. continue;
  23163. }
  23164. // #endif
  23165. pos = line.indexOf("#endif");
  23166. if (pos !== -1) {
  23167. currentNode = currentNode.parent;
  23168. continue;
  23169. }
  23170. currentNode.children.push(line);
  23171. }
  23172. // Recombine
  23173. return this._recombineShader(root);
  23174. };
  23175. return Effect;
  23176. }());
  23177. Effect._uniqueIdSeed = 0;
  23178. Effect._baseCache = {};
  23179. // Statics
  23180. Effect.ShadersStore = {};
  23181. Effect.IncludesShadersStore = {};
  23182. BABYLON.Effect = Effect;
  23183. })(BABYLON || (BABYLON = {}));
  23184. //# sourceMappingURL=babylon.effect.js.map
  23185. var BABYLON;
  23186. (function (BABYLON) {
  23187. var MaterialHelper = (function () {
  23188. function MaterialHelper() {
  23189. }
  23190. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  23191. if (defines._areMiscDirty) {
  23192. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  23193. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  23194. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  23195. defines["USERIGHTHANDEDSYSTEM"] = scene.useRightHandedSystem;
  23196. }
  23197. };
  23198. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances) {
  23199. var changed = false;
  23200. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  23201. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  23202. changed = true;
  23203. }
  23204. if (defines["ALPHATEST"] !== engine.getAlphaTesting()) {
  23205. defines["ALPHATEST"] = !defines["ALPHATEST"];
  23206. changed = true;
  23207. }
  23208. if (defines["INSTANCES"] !== useInstances) {
  23209. defines["INSTANCES"] = useInstances;
  23210. changed = true;
  23211. }
  23212. if (changed) {
  23213. defines.markAsUnprocessed();
  23214. }
  23215. };
  23216. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  23217. if (useMorphTargets === void 0) { useMorphTargets = false; }
  23218. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  23219. return;
  23220. }
  23221. defines._normals = defines._needNormals;
  23222. defines._uvs = defines._needUVs;
  23223. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  23224. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  23225. defines["TANGENT"] = true;
  23226. }
  23227. if (defines._needUVs) {
  23228. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  23229. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  23230. }
  23231. else {
  23232. defines["UV1"] = false;
  23233. defines["UV2"] = false;
  23234. }
  23235. if (useVertexColor) {
  23236. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  23237. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  23238. }
  23239. if (useBones) {
  23240. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  23241. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  23242. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  23243. }
  23244. else {
  23245. defines["NUM_BONE_INFLUENCERS"] = 0;
  23246. defines["BonesPerMesh"] = 0;
  23247. }
  23248. }
  23249. if (useMorphTargets) {
  23250. if (mesh.morphTargetManager) {
  23251. var manager = mesh.morphTargetManager;
  23252. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  23253. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  23254. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  23255. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  23256. }
  23257. else {
  23258. defines["MORPHTARGETS_TANGENT"] = false;
  23259. defines["MORPHTARGETS_NORMAL"] = false;
  23260. defines["MORPHTARGETS"] = false;
  23261. defines["NUM_MORPH_INFLUENCERS"] = 0;
  23262. }
  23263. }
  23264. };
  23265. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  23266. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23267. if (disableLighting === void 0) { disableLighting = false; }
  23268. if (!defines._areLightsDirty) {
  23269. return defines._needNormals;
  23270. }
  23271. var lightIndex = 0;
  23272. var needNormals = false;
  23273. var needRebuild = false;
  23274. var lightmapMode = false;
  23275. var shadowEnabled = false;
  23276. var specularEnabled = false;
  23277. if (scene.lightsEnabled && !disableLighting) {
  23278. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  23279. var light = _a[_i];
  23280. needNormals = true;
  23281. if (defines["LIGHT" + lightIndex] === undefined) {
  23282. needRebuild = true;
  23283. }
  23284. defines["LIGHT" + lightIndex] = true;
  23285. defines["SPOTLIGHT" + lightIndex] = false;
  23286. defines["HEMILIGHT" + lightIndex] = false;
  23287. defines["POINTLIGHT" + lightIndex] = false;
  23288. defines["DIRLIGHT" + lightIndex] = false;
  23289. var type;
  23290. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  23291. type = "SPOTLIGHT" + lightIndex;
  23292. }
  23293. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  23294. type = "HEMILIGHT" + lightIndex;
  23295. }
  23296. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  23297. type = "POINTLIGHT" + lightIndex;
  23298. }
  23299. else {
  23300. type = "DIRLIGHT" + lightIndex;
  23301. }
  23302. defines[type] = true;
  23303. // Specular
  23304. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  23305. specularEnabled = true;
  23306. }
  23307. // Shadows
  23308. defines["SHADOW" + lightIndex] = false;
  23309. defines["SHADOWPCF" + lightIndex] = false;
  23310. defines["SHADOWESM" + lightIndex] = false;
  23311. defines["SHADOWCUBE" + lightIndex] = false;
  23312. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  23313. var shadowGenerator = light.getShadowGenerator();
  23314. if (shadowGenerator) {
  23315. shadowEnabled = true;
  23316. shadowGenerator.prepareDefines(defines, lightIndex);
  23317. }
  23318. }
  23319. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  23320. lightmapMode = true;
  23321. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  23322. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  23323. }
  23324. else {
  23325. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  23326. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  23327. }
  23328. lightIndex++;
  23329. if (lightIndex === maxSimultaneousLights)
  23330. break;
  23331. }
  23332. }
  23333. defines["SPECULARTERM"] = specularEnabled;
  23334. defines["SHADOWS"] = shadowEnabled;
  23335. // Resetting all other lights if any
  23336. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  23337. if (defines["LIGHT" + index] !== undefined) {
  23338. defines["LIGHT" + index] = false;
  23339. }
  23340. }
  23341. var caps = scene.getEngine().getCaps();
  23342. if (defines["SHADOWFULLFLOAT"] === undefined) {
  23343. needRebuild = true;
  23344. }
  23345. defines["SHADOWFULLFLOAT"] = (shadowEnabled && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender);
  23346. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  23347. if (needRebuild) {
  23348. defines.rebuild();
  23349. }
  23350. return needNormals;
  23351. };
  23352. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  23353. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23354. var uniformsList, uniformBuffersList, samplersList, defines;
  23355. if (uniformsListOrOptions.uniformsNames) {
  23356. var options = uniformsListOrOptions;
  23357. uniformsList = options.uniformsNames;
  23358. uniformBuffersList = options.uniformBuffersNames;
  23359. samplersList = options.samplers;
  23360. defines = options.defines;
  23361. maxSimultaneousLights = options.maxSimultaneousLights;
  23362. }
  23363. else {
  23364. uniformsList = uniformsListOrOptions;
  23365. }
  23366. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23367. if (!defines["LIGHT" + lightIndex]) {
  23368. break;
  23369. }
  23370. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  23371. if (uniformBuffersList) {
  23372. uniformBuffersList.push("Light" + lightIndex);
  23373. }
  23374. samplersList.push("shadowSampler" + lightIndex);
  23375. }
  23376. if (defines["NUM_MORPH_INFLUENCERS"]) {
  23377. uniformsList.push("morphTargetInfluences");
  23378. }
  23379. };
  23380. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  23381. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23382. if (!defines["SHADOWS"]) {
  23383. return;
  23384. }
  23385. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  23386. if (!defines["LIGHT" + lightIndex]) {
  23387. break;
  23388. }
  23389. if (lightIndex > 0) {
  23390. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  23391. }
  23392. if (defines["SHADOW" + lightIndex]) {
  23393. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  23394. }
  23395. if (defines["SHADOWPCF" + lightIndex]) {
  23396. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  23397. }
  23398. if (defines["SHADOWESM" + lightIndex]) {
  23399. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  23400. }
  23401. }
  23402. };
  23403. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  23404. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  23405. if (influencers > 0) {
  23406. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  23407. var manager = mesh.morphTargetManager;
  23408. var normal = manager.supportsNormals && defines["NORMAL"];
  23409. var tangent = manager.supportsTangents && defines["TANGENT"];
  23410. for (var index = 0; index < influencers; index++) {
  23411. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  23412. if (normal) {
  23413. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  23414. }
  23415. if (tangent) {
  23416. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  23417. }
  23418. if (attribs.length > maxAttributesCount) {
  23419. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  23420. }
  23421. }
  23422. }
  23423. };
  23424. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  23425. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  23426. fallbacks.addCPUSkinningFallback(0, mesh);
  23427. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23428. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23429. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  23430. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  23431. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  23432. }
  23433. }
  23434. };
  23435. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  23436. if (defines["INSTANCES"]) {
  23437. attribs.push("world0");
  23438. attribs.push("world1");
  23439. attribs.push("world2");
  23440. attribs.push("world3");
  23441. }
  23442. };
  23443. // Bindings
  23444. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  23445. if (light.shadowEnabled && mesh.receiveShadows) {
  23446. var shadowGenerator = light.getShadowGenerator();
  23447. if (shadowGenerator) {
  23448. depthValuesAlreadySet = shadowGenerator.bindShadowLight(lightIndex, effect, depthValuesAlreadySet);
  23449. }
  23450. }
  23451. return depthValuesAlreadySet;
  23452. };
  23453. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  23454. light.transferToEffect(effect, lightIndex + "");
  23455. };
  23456. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  23457. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  23458. var lightIndex = 0;
  23459. var depthValuesAlreadySet = false;
  23460. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  23461. var light = _a[_i];
  23462. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  23463. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  23464. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  23465. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], light.range, lightIndex + "");
  23466. if (defines["SPECULARTERM"]) {
  23467. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  23468. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  23469. }
  23470. // Shadows
  23471. if (scene.shadowsEnabled) {
  23472. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex + "", effect, depthValuesAlreadySet);
  23473. }
  23474. light._uniformBuffer.update();
  23475. lightIndex++;
  23476. if (lightIndex === maxSimultaneousLights)
  23477. break;
  23478. }
  23479. };
  23480. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  23481. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  23482. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  23483. effect.setColor3("vFogColor", scene.fogColor);
  23484. }
  23485. };
  23486. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  23487. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  23488. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  23489. if (matrices) {
  23490. effect.setMatrices("mBones", matrices);
  23491. }
  23492. }
  23493. };
  23494. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  23495. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  23496. return;
  23497. }
  23498. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  23499. };
  23500. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  23501. if (defines["LOGARITHMICDEPTH"]) {
  23502. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  23503. }
  23504. };
  23505. MaterialHelper.BindClipPlane = function (effect, scene) {
  23506. if (scene.clipPlane) {
  23507. var clipPlane = scene.clipPlane;
  23508. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  23509. }
  23510. };
  23511. return MaterialHelper;
  23512. }());
  23513. BABYLON.MaterialHelper = MaterialHelper;
  23514. })(BABYLON || (BABYLON = {}));
  23515. //# sourceMappingURL=babylon.materialHelper.js.map
  23516. var BABYLON;
  23517. (function (BABYLON) {
  23518. var MaterialDefines = (function () {
  23519. function MaterialDefines() {
  23520. this._isDirty = true;
  23521. this._areLightsDirty = true;
  23522. this._areAttributesDirty = true;
  23523. this._areTexturesDirty = true;
  23524. this._areFresnelDirty = true;
  23525. this._areMiscDirty = true;
  23526. this._normals = false;
  23527. this._uvs = false;
  23528. this._needNormals = false;
  23529. this._needUVs = false;
  23530. }
  23531. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  23532. get: function () {
  23533. return this._isDirty;
  23534. },
  23535. enumerable: true,
  23536. configurable: true
  23537. });
  23538. MaterialDefines.prototype.markAsProcessed = function () {
  23539. this._isDirty = false;
  23540. this._areAttributesDirty = false;
  23541. this._areTexturesDirty = false;
  23542. this._areFresnelDirty = false;
  23543. this._areLightsDirty = false;
  23544. this._areMiscDirty = false;
  23545. };
  23546. MaterialDefines.prototype.markAsUnprocessed = function () {
  23547. this._isDirty = true;
  23548. };
  23549. MaterialDefines.prototype.markAllAsDirty = function () {
  23550. this._areTexturesDirty = true;
  23551. this._areAttributesDirty = true;
  23552. this._areLightsDirty = true;
  23553. this._areFresnelDirty = true;
  23554. this._areMiscDirty = true;
  23555. this._isDirty = true;
  23556. };
  23557. MaterialDefines.prototype.markAsLightDirty = function () {
  23558. this._areLightsDirty = true;
  23559. this._isDirty = true;
  23560. };
  23561. MaterialDefines.prototype.markAsAttributesDirty = function () {
  23562. this._areAttributesDirty = true;
  23563. this._isDirty = true;
  23564. };
  23565. MaterialDefines.prototype.markAsTexturesDirty = function () {
  23566. this._areTexturesDirty = true;
  23567. this._isDirty = true;
  23568. };
  23569. MaterialDefines.prototype.markAsFresnelDirty = function () {
  23570. this._areFresnelDirty = true;
  23571. this._isDirty = true;
  23572. };
  23573. MaterialDefines.prototype.markAsMiscDirty = function () {
  23574. this._areMiscDirty = true;
  23575. this._isDirty = true;
  23576. };
  23577. MaterialDefines.prototype.rebuild = function () {
  23578. if (this._keys) {
  23579. delete this._keys;
  23580. }
  23581. this._keys = [];
  23582. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  23583. var key = _a[_i];
  23584. if (key[0] === "_") {
  23585. continue;
  23586. }
  23587. this._keys.push(key);
  23588. }
  23589. };
  23590. MaterialDefines.prototype.isEqual = function (other) {
  23591. if (this._keys.length !== other._keys.length) {
  23592. return false;
  23593. }
  23594. for (var index = 0; index < this._keys.length; index++) {
  23595. var prop = this._keys[index];
  23596. if (this[prop] !== other[prop]) {
  23597. return false;
  23598. }
  23599. }
  23600. return true;
  23601. };
  23602. MaterialDefines.prototype.cloneTo = function (other) {
  23603. if (this._keys.length !== other._keys.length) {
  23604. other._keys = this._keys.slice(0);
  23605. }
  23606. for (var index = 0; index < this._keys.length; index++) {
  23607. var prop = this._keys[index];
  23608. other[prop] = this[prop];
  23609. }
  23610. };
  23611. MaterialDefines.prototype.reset = function () {
  23612. for (var index = 0; index < this._keys.length; index++) {
  23613. var prop = this._keys[index];
  23614. if (typeof (this[prop]) === "number") {
  23615. this[prop] = 0;
  23616. }
  23617. else {
  23618. this[prop] = false;
  23619. }
  23620. }
  23621. };
  23622. MaterialDefines.prototype.toString = function () {
  23623. var result = "";
  23624. for (var index = 0; index < this._keys.length; index++) {
  23625. var prop = this._keys[index];
  23626. var value = this[prop];
  23627. if (typeof (value) === "number") {
  23628. result += "#define " + prop + " " + this[prop] + "\n";
  23629. }
  23630. else if (value) {
  23631. result += "#define " + prop + "\n";
  23632. }
  23633. }
  23634. return result;
  23635. };
  23636. return MaterialDefines;
  23637. }());
  23638. BABYLON.MaterialDefines = MaterialDefines;
  23639. var Material = (function () {
  23640. function Material(name, scene, doNotAdd) {
  23641. this.checkReadyOnEveryCall = false;
  23642. this.checkReadyOnlyOnce = false;
  23643. this.state = "";
  23644. this.alpha = 1.0;
  23645. this._backFaceCulling = true;
  23646. this.doNotSerialize = false;
  23647. this.storeEffectOnSubMeshes = false;
  23648. /**
  23649. * An event triggered when the material is disposed.
  23650. * @type {BABYLON.Observable}
  23651. */
  23652. this.onDisposeObservable = new BABYLON.Observable();
  23653. /**
  23654. * An event triggered when the material is bound.
  23655. * @type {BABYLON.Observable}
  23656. */
  23657. this.onBindObservable = new BABYLON.Observable();
  23658. /**
  23659. * An event triggered when the material is unbound.
  23660. * @type {BABYLON.Observable}
  23661. */
  23662. this.onUnBindObservable = new BABYLON.Observable();
  23663. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  23664. this.disableDepthWrite = false;
  23665. this._fogEnabled = true;
  23666. this.pointSize = 1.0;
  23667. this.zOffset = 0;
  23668. this._wasPreviouslyReady = false;
  23669. this._fillMode = Material.TriangleFillMode;
  23670. this.name = name;
  23671. this.id = name;
  23672. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  23673. if (this._scene.useRightHandedSystem) {
  23674. this.sideOrientation = Material.ClockWiseSideOrientation;
  23675. }
  23676. else {
  23677. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  23678. }
  23679. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  23680. this._useUBO = this.getScene().getEngine().webGLVersion > 1;
  23681. if (!doNotAdd) {
  23682. this._scene.materials.push(this);
  23683. }
  23684. }
  23685. Object.defineProperty(Material, "TriangleFillMode", {
  23686. get: function () {
  23687. return Material._TriangleFillMode;
  23688. },
  23689. enumerable: true,
  23690. configurable: true
  23691. });
  23692. Object.defineProperty(Material, "WireFrameFillMode", {
  23693. get: function () {
  23694. return Material._WireFrameFillMode;
  23695. },
  23696. enumerable: true,
  23697. configurable: true
  23698. });
  23699. Object.defineProperty(Material, "PointFillMode", {
  23700. get: function () {
  23701. return Material._PointFillMode;
  23702. },
  23703. enumerable: true,
  23704. configurable: true
  23705. });
  23706. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  23707. get: function () {
  23708. return Material._ClockWiseSideOrientation;
  23709. },
  23710. enumerable: true,
  23711. configurable: true
  23712. });
  23713. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  23714. get: function () {
  23715. return Material._CounterClockWiseSideOrientation;
  23716. },
  23717. enumerable: true,
  23718. configurable: true
  23719. });
  23720. Object.defineProperty(Material, "TextureDirtyFlag", {
  23721. get: function () {
  23722. return Material._TextureDirtyFlag;
  23723. },
  23724. enumerable: true,
  23725. configurable: true
  23726. });
  23727. Object.defineProperty(Material, "LightDirtyFlag", {
  23728. get: function () {
  23729. return Material._LightDirtyFlag;
  23730. },
  23731. enumerable: true,
  23732. configurable: true
  23733. });
  23734. Object.defineProperty(Material, "FresnelDirtyFlag", {
  23735. get: function () {
  23736. return Material._FresnelDirtyFlag;
  23737. },
  23738. enumerable: true,
  23739. configurable: true
  23740. });
  23741. Object.defineProperty(Material, "AttributesDirtyFlag", {
  23742. get: function () {
  23743. return Material._AttributesDirtyFlag;
  23744. },
  23745. enumerable: true,
  23746. configurable: true
  23747. });
  23748. Object.defineProperty(Material, "MiscDirtyFlag", {
  23749. get: function () {
  23750. return Material._MiscDirtyFlag;
  23751. },
  23752. enumerable: true,
  23753. configurable: true
  23754. });
  23755. Object.defineProperty(Material.prototype, "backFaceCulling", {
  23756. get: function () {
  23757. return this._backFaceCulling;
  23758. },
  23759. set: function (value) {
  23760. if (this._backFaceCulling === value) {
  23761. return;
  23762. }
  23763. this._backFaceCulling = value;
  23764. this.markAsDirty(Material.TextureDirtyFlag);
  23765. },
  23766. enumerable: true,
  23767. configurable: true
  23768. });
  23769. Object.defineProperty(Material.prototype, "onDispose", {
  23770. set: function (callback) {
  23771. if (this._onDisposeObserver) {
  23772. this.onDisposeObservable.remove(this._onDisposeObserver);
  23773. }
  23774. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23775. },
  23776. enumerable: true,
  23777. configurable: true
  23778. });
  23779. Object.defineProperty(Material.prototype, "onBind", {
  23780. set: function (callback) {
  23781. if (this._onBindObserver) {
  23782. this.onBindObservable.remove(this._onBindObserver);
  23783. }
  23784. this._onBindObserver = this.onBindObservable.add(callback);
  23785. },
  23786. enumerable: true,
  23787. configurable: true
  23788. });
  23789. Object.defineProperty(Material.prototype, "fogEnabled", {
  23790. get: function () {
  23791. return this._fogEnabled;
  23792. },
  23793. set: function (value) {
  23794. if (this._fogEnabled === value) {
  23795. return;
  23796. }
  23797. this._fogEnabled = value;
  23798. this.markAsDirty(Material.MiscDirtyFlag);
  23799. },
  23800. enumerable: true,
  23801. configurable: true
  23802. });
  23803. Object.defineProperty(Material.prototype, "wireframe", {
  23804. get: function () {
  23805. return this._fillMode === Material.WireFrameFillMode;
  23806. },
  23807. set: function (value) {
  23808. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  23809. },
  23810. enumerable: true,
  23811. configurable: true
  23812. });
  23813. Object.defineProperty(Material.prototype, "pointsCloud", {
  23814. get: function () {
  23815. return this._fillMode === Material.PointFillMode;
  23816. },
  23817. set: function (value) {
  23818. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  23819. },
  23820. enumerable: true,
  23821. configurable: true
  23822. });
  23823. Object.defineProperty(Material.prototype, "fillMode", {
  23824. get: function () {
  23825. return this._fillMode;
  23826. },
  23827. set: function (value) {
  23828. if (this._fillMode === value) {
  23829. return;
  23830. }
  23831. this._fillMode = value;
  23832. this.markAsDirty(Material.MiscDirtyFlag);
  23833. },
  23834. enumerable: true,
  23835. configurable: true
  23836. });
  23837. /**
  23838. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23839. * subclasses should override adding information pertainent to themselves
  23840. */
  23841. Material.prototype.toString = function (fullDetails) {
  23842. var ret = "Name: " + this.name;
  23843. if (fullDetails) {
  23844. }
  23845. return ret;
  23846. };
  23847. /**
  23848. * Child classes can use it to update shaders
  23849. */
  23850. Material.prototype.markAsDirty = function (flag) {
  23851. };
  23852. Material.prototype.getClassName = function () {
  23853. return "Material";
  23854. };
  23855. Object.defineProperty(Material.prototype, "isFrozen", {
  23856. get: function () {
  23857. return this.checkReadyOnlyOnce;
  23858. },
  23859. enumerable: true,
  23860. configurable: true
  23861. });
  23862. Material.prototype.freeze = function () {
  23863. this.checkReadyOnlyOnce = true;
  23864. };
  23865. Material.prototype.unfreeze = function () {
  23866. this.checkReadyOnlyOnce = false;
  23867. };
  23868. Material.prototype.isReady = function (mesh, useInstances) {
  23869. return true;
  23870. };
  23871. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  23872. return false;
  23873. };
  23874. Material.prototype.getEffect = function () {
  23875. return this._effect;
  23876. };
  23877. Material.prototype.getScene = function () {
  23878. return this._scene;
  23879. };
  23880. Material.prototype.needAlphaBlending = function () {
  23881. return (this.alpha < 1.0);
  23882. };
  23883. Material.prototype.needAlphaTesting = function () {
  23884. return false;
  23885. };
  23886. Material.prototype.getAlphaTestTexture = function () {
  23887. return null;
  23888. };
  23889. Material.prototype.markDirty = function () {
  23890. this._wasPreviouslyReady = false;
  23891. };
  23892. Material.prototype._preBind = function (effect) {
  23893. var engine = this._scene.getEngine();
  23894. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  23895. engine.enableEffect(effect ? effect : this._effect);
  23896. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  23897. };
  23898. Material.prototype.bind = function (world, mesh) {
  23899. };
  23900. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  23901. };
  23902. Material.prototype.bindOnlyWorldMatrix = function (world) {
  23903. };
  23904. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  23905. sceneUbo.bindToEffect(effect, "Scene");
  23906. };
  23907. Material.prototype.bindView = function (effect) {
  23908. if (!this._useUBO) {
  23909. effect.setMatrix("view", this.getScene().getViewMatrix());
  23910. }
  23911. else {
  23912. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  23913. }
  23914. };
  23915. Material.prototype.bindViewProjection = function (effect) {
  23916. if (!this._useUBO) {
  23917. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  23918. }
  23919. else {
  23920. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  23921. }
  23922. };
  23923. Material.prototype._afterBind = function (mesh) {
  23924. this._scene._cachedMaterial = this;
  23925. this.onBindObservable.notifyObservers(mesh);
  23926. if (this.disableDepthWrite) {
  23927. var engine = this._scene.getEngine();
  23928. this._cachedDepthWriteState = engine.getDepthWrite();
  23929. engine.setDepthWrite(false);
  23930. }
  23931. };
  23932. Material.prototype.unbind = function () {
  23933. this.onUnBindObservable.notifyObservers(this);
  23934. if (this.disableDepthWrite) {
  23935. var engine = this._scene.getEngine();
  23936. engine.setDepthWrite(this._cachedDepthWriteState);
  23937. }
  23938. };
  23939. Material.prototype.clone = function (name) {
  23940. return null;
  23941. };
  23942. Material.prototype.getBindedMeshes = function () {
  23943. var result = new Array();
  23944. for (var index = 0; index < this._scene.meshes.length; index++) {
  23945. var mesh = this._scene.meshes[index];
  23946. if (mesh.material === this) {
  23947. result.push(mesh);
  23948. }
  23949. }
  23950. return result;
  23951. };
  23952. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  23953. // Animations
  23954. this.getScene().stopAnimation(this);
  23955. // Remove from scene
  23956. var index = this._scene.materials.indexOf(this);
  23957. if (index >= 0) {
  23958. this._scene.materials.splice(index, 1);
  23959. }
  23960. // Remove from meshes
  23961. for (index = 0; index < this._scene.meshes.length; index++) {
  23962. var mesh = this._scene.meshes[index];
  23963. if (mesh.material === this) {
  23964. mesh.material = null;
  23965. if (mesh.geometry) {
  23966. var geometry = mesh.geometry;
  23967. if (this.storeEffectOnSubMeshes) {
  23968. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  23969. var subMesh = _a[_i];
  23970. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  23971. }
  23972. }
  23973. else {
  23974. geometry._releaseVertexArrayObject(this._effect);
  23975. }
  23976. }
  23977. }
  23978. }
  23979. this._uniformBuffer.dispose();
  23980. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  23981. if (forceDisposeEffect && this._effect) {
  23982. if (this.storeEffectOnSubMeshes) {
  23983. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  23984. var subMesh = _c[_b];
  23985. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  23986. }
  23987. }
  23988. else {
  23989. this._scene.getEngine()._releaseEffect(this._effect);
  23990. }
  23991. this._effect = null;
  23992. }
  23993. // Callback
  23994. this.onDisposeObservable.notifyObservers(this);
  23995. this.onDisposeObservable.clear();
  23996. this.onBindObservable.clear();
  23997. this.onUnBindObservable.clear();
  23998. };
  23999. Material.prototype.serialize = function () {
  24000. return BABYLON.SerializationHelper.Serialize(this);
  24001. };
  24002. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  24003. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  24004. multiMaterial.id = parsedMultiMaterial.id;
  24005. if (BABYLON.Tags) {
  24006. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  24007. }
  24008. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  24009. var subMatId = parsedMultiMaterial.materials[matIndex];
  24010. if (subMatId) {
  24011. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  24012. }
  24013. else {
  24014. multiMaterial.subMaterials.push(null);
  24015. }
  24016. }
  24017. return multiMaterial;
  24018. };
  24019. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  24020. if (!parsedMaterial.customType) {
  24021. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  24022. }
  24023. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && !parsedMaterial.overloadedAlbedo) {
  24024. parsedMaterial.customType === "BABYLON.legacyPBRMaterial";
  24025. if (!BABYLON.legacyPBRMaterial) {
  24026. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  24027. return;
  24028. }
  24029. }
  24030. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  24031. return materialType.Parse(parsedMaterial, scene, rootUrl);
  24032. ;
  24033. };
  24034. return Material;
  24035. }());
  24036. Material._TriangleFillMode = 0;
  24037. Material._WireFrameFillMode = 1;
  24038. Material._PointFillMode = 2;
  24039. Material._ClockWiseSideOrientation = 0;
  24040. Material._CounterClockWiseSideOrientation = 1;
  24041. Material._TextureDirtyFlag = 1;
  24042. Material._LightDirtyFlag = 2;
  24043. Material._FresnelDirtyFlag = 4;
  24044. Material._AttributesDirtyFlag = 8;
  24045. Material._MiscDirtyFlag = 16;
  24046. __decorate([
  24047. BABYLON.serialize()
  24048. ], Material.prototype, "id", void 0);
  24049. __decorate([
  24050. BABYLON.serialize()
  24051. ], Material.prototype, "name", void 0);
  24052. __decorate([
  24053. BABYLON.serialize()
  24054. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  24055. __decorate([
  24056. BABYLON.serialize()
  24057. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  24058. __decorate([
  24059. BABYLON.serialize()
  24060. ], Material.prototype, "state", void 0);
  24061. __decorate([
  24062. BABYLON.serialize()
  24063. ], Material.prototype, "alpha", void 0);
  24064. __decorate([
  24065. BABYLON.serialize("backFaceCulling")
  24066. ], Material.prototype, "_backFaceCulling", void 0);
  24067. __decorate([
  24068. BABYLON.serialize()
  24069. ], Material.prototype, "sideOrientation", void 0);
  24070. __decorate([
  24071. BABYLON.serialize()
  24072. ], Material.prototype, "alphaMode", void 0);
  24073. __decorate([
  24074. BABYLON.serialize()
  24075. ], Material.prototype, "disableDepthWrite", void 0);
  24076. __decorate([
  24077. BABYLON.serialize("fogEnabled")
  24078. ], Material.prototype, "_fogEnabled", void 0);
  24079. __decorate([
  24080. BABYLON.serialize()
  24081. ], Material.prototype, "pointSize", void 0);
  24082. __decorate([
  24083. BABYLON.serialize()
  24084. ], Material.prototype, "zOffset", void 0);
  24085. __decorate([
  24086. BABYLON.serialize()
  24087. ], Material.prototype, "wireframe", null);
  24088. __decorate([
  24089. BABYLON.serialize()
  24090. ], Material.prototype, "pointsCloud", null);
  24091. __decorate([
  24092. BABYLON.serialize()
  24093. ], Material.prototype, "fillMode", null);
  24094. BABYLON.Material = Material;
  24095. })(BABYLON || (BABYLON = {}));
  24096. //# sourceMappingURL=babylon.material.js.map
  24097. var BABYLON;
  24098. (function (BABYLON) {
  24099. var UniformBuffer = (function () {
  24100. /**
  24101. * Uniform buffer objects.
  24102. *
  24103. * Handles blocks of uniform on the GPU.
  24104. *
  24105. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  24106. *
  24107. * For more information, please refer to :
  24108. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  24109. */
  24110. function UniformBuffer(engine, data, dynamic) {
  24111. this._engine = engine;
  24112. this._noUBO = engine.webGLVersion === 1;
  24113. this._dynamic = dynamic;
  24114. this._data = data || [];
  24115. this._uniformLocations = {};
  24116. this._uniformSizes = {};
  24117. this._uniformLocationPointer = 0;
  24118. this._needSync = false;
  24119. if (this._noUBO) {
  24120. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  24121. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  24122. this.updateFloat = this._updateFloatForEffect;
  24123. this.updateFloat2 = this._updateFloat2ForEffect;
  24124. this.updateFloat3 = this._updateFloat3ForEffect;
  24125. this.updateFloat4 = this._updateFloat4ForEffect;
  24126. this.updateMatrix = this._updateMatrixForEffect;
  24127. this.updateVector3 = this._updateVector3ForEffect;
  24128. this.updateVector4 = this._updateVector4ForEffect;
  24129. this.updateColor3 = this._updateColor3ForEffect;
  24130. this.updateColor4 = this._updateColor4ForEffect;
  24131. }
  24132. else {
  24133. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  24134. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  24135. this.updateFloat = this._updateFloatForUniform;
  24136. this.updateFloat2 = this._updateFloat2ForUniform;
  24137. this.updateFloat3 = this._updateFloat3ForUniform;
  24138. this.updateFloat4 = this._updateFloat4ForUniform;
  24139. this.updateMatrix = this._updateMatrixForUniform;
  24140. this.updateVector3 = this._updateVector3ForUniform;
  24141. this.updateVector4 = this._updateVector4ForUniform;
  24142. this.updateColor3 = this._updateColor3ForUniform;
  24143. this.updateColor4 = this._updateColor4ForUniform;
  24144. }
  24145. }
  24146. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  24147. // Properties
  24148. /**
  24149. * Indicates if the buffer is using the WebGL2 UBO implementation,
  24150. * or just falling back on setUniformXXX calls.
  24151. */
  24152. get: function () {
  24153. return !this._noUBO;
  24154. },
  24155. enumerable: true,
  24156. configurable: true
  24157. });
  24158. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  24159. /**
  24160. * Indicates if the WebGL underlying uniform buffer is in sync
  24161. * with the javascript cache data.
  24162. */
  24163. get: function () {
  24164. return !this._needSync;
  24165. },
  24166. enumerable: true,
  24167. configurable: true
  24168. });
  24169. /**
  24170. * Indicates if the WebGL underlying uniform buffer is dynamic.
  24171. * Also, a dynamic UniformBuffer will disable cache verification and always
  24172. * update the underlying WebGL uniform buffer to the GPU.
  24173. */
  24174. UniformBuffer.prototype.isDynamic = function () {
  24175. return this._dynamic;
  24176. };
  24177. /**
  24178. * The data cache on JS side.
  24179. */
  24180. UniformBuffer.prototype.getData = function () {
  24181. return this._bufferData;
  24182. };
  24183. /**
  24184. * The underlying WebGL Uniform buffer.
  24185. */
  24186. UniformBuffer.prototype.getBuffer = function () {
  24187. return this._buffer;
  24188. };
  24189. /**
  24190. * std140 layout specifies how to align data within an UBO structure.
  24191. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  24192. * for specs.
  24193. */
  24194. UniformBuffer.prototype._fillAlignment = function (size) {
  24195. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  24196. // and 4x4 matrices
  24197. // TODO : change if other types are used
  24198. var alignment;
  24199. if (size <= 2) {
  24200. alignment = size;
  24201. }
  24202. else {
  24203. alignment = 4;
  24204. }
  24205. if ((this._uniformLocationPointer % alignment) !== 0) {
  24206. var oldPointer = this._uniformLocationPointer;
  24207. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  24208. var diff = this._uniformLocationPointer - oldPointer;
  24209. for (var i = 0; i < diff; i++) {
  24210. this._data.push(0);
  24211. }
  24212. }
  24213. };
  24214. /**
  24215. * Adds an uniform in the buffer.
  24216. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  24217. * for the layout to be correct !
  24218. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24219. * @param {number|number[]} size Data size, or data directly.
  24220. */
  24221. UniformBuffer.prototype.addUniform = function (name, size) {
  24222. if (this._noUBO) {
  24223. return;
  24224. }
  24225. if (this._uniformLocations[name] !== undefined) {
  24226. // Already existing uniform
  24227. return;
  24228. }
  24229. // This function must be called in the order of the shader layout !
  24230. // size can be the size of the uniform, or data directly
  24231. var data;
  24232. if (size instanceof Array) {
  24233. data = size;
  24234. size = data.length;
  24235. }
  24236. else {
  24237. size = size;
  24238. data = [];
  24239. // Fill with zeros
  24240. for (var i = 0; i < size; i++) {
  24241. data.push(0);
  24242. }
  24243. }
  24244. this._fillAlignment(size);
  24245. this._uniformSizes[name] = size;
  24246. this._uniformLocations[name] = this._uniformLocationPointer;
  24247. this._uniformLocationPointer += size;
  24248. for (var i = 0; i < size; i++) {
  24249. this._data.push(data[i]);
  24250. }
  24251. this._needSync = true;
  24252. };
  24253. /**
  24254. * Wrapper for addUniform.
  24255. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24256. * @param {Matrix} mat A 4x4 matrix.
  24257. */
  24258. UniformBuffer.prototype.addMatrix = function (name, mat) {
  24259. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  24260. };
  24261. /**
  24262. * Wrapper for addUniform.
  24263. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24264. * @param {number} x
  24265. * @param {number} y
  24266. */
  24267. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  24268. var temp = [x, y];
  24269. this.addUniform(name, temp);
  24270. };
  24271. /**
  24272. * Wrapper for addUniform.
  24273. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24274. * @param {number} x
  24275. * @param {number} y
  24276. * @param {number} z
  24277. */
  24278. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  24279. var temp = [x, y, z];
  24280. this.addUniform(name, temp);
  24281. };
  24282. /**
  24283. * Wrapper for addUniform.
  24284. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24285. * @param {Color3} color
  24286. */
  24287. UniformBuffer.prototype.addColor3 = function (name, color) {
  24288. var temp = [];
  24289. color.toArray(temp);
  24290. this.addUniform(name, temp);
  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 {Color3} color
  24296. * @param {number} alpha
  24297. */
  24298. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  24299. var temp = [];
  24300. color.toArray(temp);
  24301. temp.push(alpha);
  24302. this.addUniform(name, temp);
  24303. };
  24304. /**
  24305. * Wrapper for addUniform.
  24306. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24307. * @param {Vector3} vector
  24308. */
  24309. UniformBuffer.prototype.addVector3 = function (name, vector) {
  24310. var temp = [];
  24311. vector.toArray(temp);
  24312. this.addUniform(name, temp);
  24313. };
  24314. /**
  24315. * Wrapper for addUniform.
  24316. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24317. */
  24318. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  24319. this.addUniform(name, 12);
  24320. };
  24321. /**
  24322. * Wrapper for addUniform.
  24323. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  24324. */
  24325. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  24326. this.addUniform(name, 8);
  24327. };
  24328. /**
  24329. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  24330. */
  24331. UniformBuffer.prototype.create = function () {
  24332. if (this._noUBO) {
  24333. return;
  24334. }
  24335. if (this._buffer) {
  24336. return; // nothing to do
  24337. }
  24338. // See spec, alignment must be filled as a vec4
  24339. this._fillAlignment(4);
  24340. this._bufferData = new Float32Array(this._data);
  24341. if (this._dynamic) {
  24342. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  24343. }
  24344. else {
  24345. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  24346. }
  24347. this._needSync = true;
  24348. };
  24349. /**
  24350. * Updates the WebGL Uniform Buffer on the GPU.
  24351. * If the `dynamic` flag is set to true, no cache comparison is done.
  24352. * Otherwise, the buffer will be updated only if the cache differs.
  24353. */
  24354. UniformBuffer.prototype.update = function () {
  24355. if (!this._buffer) {
  24356. this.create();
  24357. return;
  24358. }
  24359. if (!this._dynamic && !this._needSync) {
  24360. return;
  24361. }
  24362. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  24363. this._needSync = false;
  24364. };
  24365. /**
  24366. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  24367. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  24368. * @param {number[]|Float32Array} data Flattened data
  24369. * @param {number} size Size of the data.
  24370. */
  24371. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  24372. var location = this._uniformLocations[uniformName];
  24373. if (location === undefined) {
  24374. if (this._buffer) {
  24375. // Cannot add an uniform if the buffer is already created
  24376. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  24377. return;
  24378. }
  24379. this.addUniform(uniformName, size);
  24380. location = this._uniformLocations[uniformName];
  24381. }
  24382. if (!this._buffer) {
  24383. this.create();
  24384. }
  24385. if (!this._dynamic) {
  24386. // Cache for static uniform buffers
  24387. var changed = false;
  24388. for (var i = 0; i < size; i++) {
  24389. if (this._bufferData[location + i] !== data[i]) {
  24390. changed = true;
  24391. this._bufferData[location + i] = data[i];
  24392. }
  24393. }
  24394. this._needSync = this._needSync || changed;
  24395. }
  24396. else {
  24397. // No cache for dynamic
  24398. for (var i = 0; i < size; i++) {
  24399. this._bufferData[location + i] = data[i];
  24400. }
  24401. }
  24402. };
  24403. // Update methods
  24404. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  24405. // To match std140, matrix must be realigned
  24406. for (var i = 0; i < 3; i++) {
  24407. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  24408. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  24409. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  24410. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  24411. }
  24412. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  24413. };
  24414. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  24415. this._currentEffect.setMatrix3x3(name, matrix);
  24416. };
  24417. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  24418. this._currentEffect.setMatrix2x2(name, matrix);
  24419. };
  24420. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  24421. // To match std140, matrix must be realigned
  24422. for (var i = 0; i < 2; i++) {
  24423. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  24424. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  24425. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  24426. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  24427. }
  24428. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  24429. };
  24430. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  24431. this._currentEffect.setFloat(name, x);
  24432. };
  24433. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  24434. UniformBuffer._tempBuffer[0] = x;
  24435. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  24436. };
  24437. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y) {
  24438. this._currentEffect.setFloat2(name, x, y);
  24439. };
  24440. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y) {
  24441. UniformBuffer._tempBuffer[0] = x;
  24442. UniformBuffer._tempBuffer[1] = y;
  24443. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  24444. };
  24445. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  24446. if (suffix === void 0) { suffix = ""; }
  24447. this._currentEffect.setFloat3(name + suffix, x, y, z);
  24448. };
  24449. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  24450. if (suffix === void 0) { suffix = ""; }
  24451. UniformBuffer._tempBuffer[0] = x;
  24452. UniformBuffer._tempBuffer[1] = y;
  24453. UniformBuffer._tempBuffer[2] = z;
  24454. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24455. };
  24456. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  24457. if (suffix === void 0) { suffix = ""; }
  24458. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  24459. };
  24460. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  24461. if (suffix === void 0) { suffix = ""; }
  24462. UniformBuffer._tempBuffer[0] = x;
  24463. UniformBuffer._tempBuffer[1] = y;
  24464. UniformBuffer._tempBuffer[2] = z;
  24465. UniformBuffer._tempBuffer[3] = w;
  24466. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24467. };
  24468. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  24469. this._currentEffect.setMatrix(name, mat);
  24470. };
  24471. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  24472. this.updateUniform(name, mat.toArray(), 16);
  24473. };
  24474. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  24475. this._currentEffect.setVector3(name, vector);
  24476. };
  24477. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  24478. vector.toArray(UniformBuffer._tempBuffer);
  24479. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24480. };
  24481. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  24482. this._currentEffect.setVector4(name, vector);
  24483. };
  24484. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  24485. vector.toArray(UniformBuffer._tempBuffer);
  24486. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24487. };
  24488. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  24489. if (suffix === void 0) { suffix = ""; }
  24490. this._currentEffect.setColor3(name + suffix, color);
  24491. };
  24492. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  24493. if (suffix === void 0) { suffix = ""; }
  24494. color.toArray(UniformBuffer._tempBuffer);
  24495. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  24496. };
  24497. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  24498. if (suffix === void 0) { suffix = ""; }
  24499. this._currentEffect.setColor4(name + suffix, color, alpha);
  24500. };
  24501. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  24502. if (suffix === void 0) { suffix = ""; }
  24503. color.toArray(UniformBuffer._tempBuffer);
  24504. UniformBuffer._tempBuffer[3] = alpha;
  24505. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  24506. };
  24507. /**
  24508. * Sets a sampler uniform on the effect.
  24509. * @param {string} name Name of the sampler.
  24510. * @param {Texture} texture
  24511. */
  24512. UniformBuffer.prototype.setTexture = function (name, texture) {
  24513. this._currentEffect.setTexture(name, texture);
  24514. };
  24515. /**
  24516. * Directly updates the value of the uniform in the cache AND on the GPU.
  24517. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  24518. * @param {number[]|Float32Array} data Flattened data
  24519. */
  24520. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  24521. this.updateUniform(uniformName, data, data.length);
  24522. this.update();
  24523. };
  24524. /**
  24525. * Binds this uniform buffer to an effect.
  24526. * @param {Effect} effect
  24527. * @param {string} name Name of the uniform block in the shader.
  24528. */
  24529. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  24530. this._currentEffect = effect;
  24531. if (this._noUBO) {
  24532. return;
  24533. }
  24534. effect.bindUniformBuffer(this._buffer, name);
  24535. };
  24536. /**
  24537. * Disposes the uniform buffer.
  24538. */
  24539. UniformBuffer.prototype.dispose = function () {
  24540. if (!this._buffer) {
  24541. return;
  24542. }
  24543. if (this._engine._releaseBuffer(this._buffer)) {
  24544. this._buffer = null;
  24545. }
  24546. };
  24547. return UniformBuffer;
  24548. }());
  24549. // Pool for avoiding memory leaks
  24550. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  24551. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  24552. BABYLON.UniformBuffer = UniformBuffer;
  24553. })(BABYLON || (BABYLON = {}));
  24554. //# sourceMappingURL=babylon.uniformBuffer.js.map
  24555. var BABYLON;
  24556. (function (BABYLON) {
  24557. var PushMaterial = (function (_super) {
  24558. __extends(PushMaterial, _super);
  24559. function PushMaterial(name, scene) {
  24560. var _this = _super.call(this, name, scene) || this;
  24561. _this.storeEffectOnSubMeshes = true;
  24562. return _this;
  24563. }
  24564. PushMaterial.prototype.getEffect = function () {
  24565. return this._activeEffect;
  24566. };
  24567. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  24568. if (!mesh) {
  24569. return false;
  24570. }
  24571. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  24572. return true;
  24573. }
  24574. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  24575. };
  24576. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  24577. this._activeEffect.setMatrix("world", world);
  24578. };
  24579. PushMaterial.prototype.bind = function (world, mesh) {
  24580. if (!mesh) {
  24581. return;
  24582. }
  24583. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  24584. };
  24585. PushMaterial.prototype._afterBind = function (mesh, effect) {
  24586. _super.prototype._afterBind.call(this, mesh);
  24587. this.getScene()._cachedEffect = effect;
  24588. };
  24589. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  24590. if (visibility === void 0) { visibility = 0; }
  24591. return scene.isCachedMaterialValid(this, effect, visibility);
  24592. };
  24593. PushMaterial.prototype.markAsDirty = function (flag) {
  24594. if (flag & BABYLON.Material.TextureDirtyFlag) {
  24595. this._markAllSubMeshesAsTexturesDirty();
  24596. }
  24597. if (flag & BABYLON.Material.LightDirtyFlag) {
  24598. this._markAllSubMeshesAsLightsDirty();
  24599. }
  24600. if (flag & BABYLON.Material.FresnelDirtyFlag) {
  24601. this._markAllSubMeshesAsFresnelDirty();
  24602. }
  24603. if (flag & BABYLON.Material.AttributesDirtyFlag) {
  24604. this._markAllSubMeshesAsAttributesDirty();
  24605. }
  24606. if (flag & BABYLON.Material.MiscDirtyFlag) {
  24607. this._markAllSubMeshesAsMiscDirty();
  24608. }
  24609. };
  24610. PushMaterial.prototype._markAllSubMeshesAsDirty = function (func) {
  24611. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  24612. var mesh = _a[_i];
  24613. if (!mesh.subMeshes) {
  24614. continue;
  24615. }
  24616. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  24617. var subMesh = _c[_b];
  24618. if (subMesh.getMaterial() !== this) {
  24619. continue;
  24620. }
  24621. if (!subMesh._materialDefines) {
  24622. return;
  24623. }
  24624. func(subMesh._materialDefines);
  24625. }
  24626. }
  24627. };
  24628. PushMaterial.prototype._markAllSubMeshesAsTexturesDirty = function () {
  24629. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  24630. };
  24631. PushMaterial.prototype._markAllSubMeshesAsFresnelDirty = function () {
  24632. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  24633. };
  24634. PushMaterial.prototype._markAllSubMeshesAsLightsDirty = function () {
  24635. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  24636. };
  24637. PushMaterial.prototype._markAllSubMeshesAsAttributesDirty = function () {
  24638. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  24639. };
  24640. PushMaterial.prototype._markAllSubMeshesAsMiscDirty = function () {
  24641. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  24642. };
  24643. return PushMaterial;
  24644. }(BABYLON.Material));
  24645. BABYLON.PushMaterial = PushMaterial;
  24646. })(BABYLON || (BABYLON = {}));
  24647. //# sourceMappingURL=babylon.pushMaterial.js.map
  24648. var BABYLON;
  24649. (function (BABYLON) {
  24650. var VertexData = (function () {
  24651. function VertexData() {
  24652. }
  24653. VertexData.prototype.set = function (data, kind) {
  24654. switch (kind) {
  24655. case BABYLON.VertexBuffer.PositionKind:
  24656. this.positions = data;
  24657. break;
  24658. case BABYLON.VertexBuffer.NormalKind:
  24659. this.normals = data;
  24660. break;
  24661. case BABYLON.VertexBuffer.TangentKind:
  24662. this.tangents = data;
  24663. break;
  24664. case BABYLON.VertexBuffer.UVKind:
  24665. this.uvs = data;
  24666. break;
  24667. case BABYLON.VertexBuffer.UV2Kind:
  24668. this.uvs2 = data;
  24669. break;
  24670. case BABYLON.VertexBuffer.UV3Kind:
  24671. this.uvs3 = data;
  24672. break;
  24673. case BABYLON.VertexBuffer.UV4Kind:
  24674. this.uvs4 = data;
  24675. break;
  24676. case BABYLON.VertexBuffer.UV5Kind:
  24677. this.uvs5 = data;
  24678. break;
  24679. case BABYLON.VertexBuffer.UV6Kind:
  24680. this.uvs6 = data;
  24681. break;
  24682. case BABYLON.VertexBuffer.ColorKind:
  24683. this.colors = data;
  24684. break;
  24685. case BABYLON.VertexBuffer.MatricesIndicesKind:
  24686. this.matricesIndices = data;
  24687. break;
  24688. case BABYLON.VertexBuffer.MatricesWeightsKind:
  24689. this.matricesWeights = data;
  24690. break;
  24691. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  24692. this.matricesIndicesExtra = data;
  24693. break;
  24694. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  24695. this.matricesWeightsExtra = data;
  24696. break;
  24697. }
  24698. };
  24699. /**
  24700. * Associates the vertexData to the passed Mesh.
  24701. * Sets it as updatable or not (default `false`).
  24702. * Returns the VertexData.
  24703. */
  24704. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  24705. this._applyTo(mesh, updatable);
  24706. return this;
  24707. };
  24708. /**
  24709. * Associates the vertexData to the passed Geometry.
  24710. * Sets it as updatable or not (default `false`).
  24711. * Returns the VertexData.
  24712. */
  24713. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  24714. this._applyTo(geometry, updatable);
  24715. return this;
  24716. };
  24717. /**
  24718. * Updates the associated mesh.
  24719. * Returns the VertexData.
  24720. */
  24721. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  24722. this._update(mesh);
  24723. return this;
  24724. };
  24725. /**
  24726. * Updates the associated geometry.
  24727. * Returns the VertexData.
  24728. */
  24729. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  24730. this._update(geometry);
  24731. return this;
  24732. };
  24733. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  24734. if (this.positions) {
  24735. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  24736. }
  24737. if (this.normals) {
  24738. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  24739. }
  24740. if (this.tangents) {
  24741. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  24742. }
  24743. if (this.uvs) {
  24744. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  24745. }
  24746. if (this.uvs2) {
  24747. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  24748. }
  24749. if (this.uvs3) {
  24750. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  24751. }
  24752. if (this.uvs4) {
  24753. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  24754. }
  24755. if (this.uvs5) {
  24756. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  24757. }
  24758. if (this.uvs6) {
  24759. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  24760. }
  24761. if (this.colors) {
  24762. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  24763. }
  24764. if (this.matricesIndices) {
  24765. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  24766. }
  24767. if (this.matricesWeights) {
  24768. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  24769. }
  24770. if (this.matricesIndicesExtra) {
  24771. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  24772. }
  24773. if (this.matricesWeightsExtra) {
  24774. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  24775. }
  24776. if (this.indices) {
  24777. meshOrGeometry.setIndices(this.indices);
  24778. }
  24779. return this;
  24780. };
  24781. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  24782. if (this.positions) {
  24783. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  24784. }
  24785. if (this.normals) {
  24786. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  24787. }
  24788. if (this.tangents) {
  24789. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  24790. }
  24791. if (this.uvs) {
  24792. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  24793. }
  24794. if (this.uvs2) {
  24795. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  24796. }
  24797. if (this.uvs3) {
  24798. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  24799. }
  24800. if (this.uvs4) {
  24801. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  24802. }
  24803. if (this.uvs5) {
  24804. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  24805. }
  24806. if (this.uvs6) {
  24807. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  24808. }
  24809. if (this.colors) {
  24810. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  24811. }
  24812. if (this.matricesIndices) {
  24813. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  24814. }
  24815. if (this.matricesWeights) {
  24816. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  24817. }
  24818. if (this.matricesIndicesExtra) {
  24819. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  24820. }
  24821. if (this.matricesWeightsExtra) {
  24822. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  24823. }
  24824. if (this.indices) {
  24825. meshOrGeometry.setIndices(this.indices);
  24826. }
  24827. return this;
  24828. };
  24829. /**
  24830. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  24831. * Returns the VertexData.
  24832. */
  24833. VertexData.prototype.transform = function (matrix) {
  24834. var transformed = BABYLON.Vector3.Zero();
  24835. var index;
  24836. if (this.positions) {
  24837. var position = BABYLON.Vector3.Zero();
  24838. for (index = 0; index < this.positions.length; index += 3) {
  24839. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  24840. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  24841. this.positions[index] = transformed.x;
  24842. this.positions[index + 1] = transformed.y;
  24843. this.positions[index + 2] = transformed.z;
  24844. }
  24845. }
  24846. if (this.normals) {
  24847. var normal = BABYLON.Vector3.Zero();
  24848. for (index = 0; index < this.normals.length; index += 3) {
  24849. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  24850. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  24851. this.normals[index] = transformed.x;
  24852. this.normals[index + 1] = transformed.y;
  24853. this.normals[index + 2] = transformed.z;
  24854. }
  24855. }
  24856. if (this.tangents) {
  24857. var tangent = BABYLON.Vector4.Zero();
  24858. var tangentTransformed = BABYLON.Vector4.Zero();
  24859. for (index = 0; index < this.tangents.length; index += 4) {
  24860. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  24861. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  24862. this.tangents[index] = tangentTransformed.x;
  24863. this.tangents[index + 1] = tangentTransformed.y;
  24864. this.tangents[index + 2] = tangentTransformed.z;
  24865. this.tangents[index + 3] = tangentTransformed.w;
  24866. }
  24867. }
  24868. return this;
  24869. };
  24870. /**
  24871. * Merges the passed VertexData into the current one.
  24872. * Returns the modified VertexData.
  24873. */
  24874. VertexData.prototype.merge = function (other) {
  24875. if (other.indices) {
  24876. if (!this.indices) {
  24877. this.indices = [];
  24878. }
  24879. var offset = this.positions ? this.positions.length / 3 : 0;
  24880. for (var index = 0; index < other.indices.length; index++) {
  24881. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  24882. this.indices.push(other.indices[index] + offset);
  24883. }
  24884. }
  24885. this.positions = this._mergeElement(this.positions, other.positions);
  24886. this.normals = this._mergeElement(this.normals, other.normals);
  24887. this.tangents = this._mergeElement(this.tangents, other.tangents);
  24888. this.uvs = this._mergeElement(this.uvs, other.uvs);
  24889. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  24890. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  24891. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  24892. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  24893. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  24894. this.colors = this._mergeElement(this.colors, other.colors);
  24895. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  24896. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  24897. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  24898. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  24899. return this;
  24900. };
  24901. VertexData.prototype._mergeElement = function (source, other) {
  24902. if (!other)
  24903. return source;
  24904. if (!source)
  24905. return other;
  24906. var len = other.length + source.length;
  24907. var isSrcTypedArray = source instanceof Float32Array;
  24908. var isOthTypedArray = other instanceof Float32Array;
  24909. // use non-loop method when the source is Float32Array
  24910. if (isSrcTypedArray) {
  24911. var ret32 = new Float32Array(len);
  24912. ret32.set(source);
  24913. ret32.set(other, source.length);
  24914. return ret32;
  24915. // source is number[], when other is also use concat
  24916. }
  24917. else if (!isOthTypedArray) {
  24918. return source.concat(other);
  24919. // source is a number[], but other is a Float32Array, loop required
  24920. }
  24921. else {
  24922. var ret = source.slice(0); // copy source to a separate array
  24923. for (var i = 0, len = other.length; i < len; i++) {
  24924. ret.push(other[i]);
  24925. }
  24926. return ret;
  24927. }
  24928. };
  24929. /**
  24930. * Serializes the VertexData.
  24931. * Returns a serialized object.
  24932. */
  24933. VertexData.prototype.serialize = function () {
  24934. var serializationObject = this.serialize();
  24935. if (this.positions) {
  24936. serializationObject.positions = this.positions;
  24937. }
  24938. if (this.normals) {
  24939. serializationObject.normals = this.normals;
  24940. }
  24941. if (this.tangents) {
  24942. serializationObject.tangents = this.tangents;
  24943. }
  24944. if (this.uvs) {
  24945. serializationObject.uvs = this.uvs;
  24946. }
  24947. if (this.uvs2) {
  24948. serializationObject.uvs2 = this.uvs2;
  24949. }
  24950. if (this.uvs3) {
  24951. serializationObject.uvs3 = this.uvs3;
  24952. }
  24953. if (this.uvs4) {
  24954. serializationObject.uvs4 = this.uvs4;
  24955. }
  24956. if (this.uvs5) {
  24957. serializationObject.uvs5 = this.uvs5;
  24958. }
  24959. if (this.uvs6) {
  24960. serializationObject.uvs6 = this.uvs6;
  24961. }
  24962. if (this.colors) {
  24963. serializationObject.colors = this.colors;
  24964. }
  24965. if (this.matricesIndices) {
  24966. serializationObject.matricesIndices = this.matricesIndices;
  24967. serializationObject.matricesIndices._isExpanded = true;
  24968. }
  24969. if (this.matricesWeights) {
  24970. serializationObject.matricesWeights = this.matricesWeights;
  24971. }
  24972. if (this.matricesIndicesExtra) {
  24973. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  24974. serializationObject.matricesIndicesExtra._isExpanded = true;
  24975. }
  24976. if (this.matricesWeightsExtra) {
  24977. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  24978. }
  24979. serializationObject.indices = this.indices;
  24980. return serializationObject;
  24981. };
  24982. // Statics
  24983. /**
  24984. * Returns the object VertexData associated to the passed mesh.
  24985. */
  24986. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  24987. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  24988. };
  24989. /**
  24990. * Returns the object VertexData associated to the passed geometry.
  24991. */
  24992. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  24993. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  24994. };
  24995. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  24996. var result = new VertexData();
  24997. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24998. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  24999. }
  25000. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25001. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  25002. }
  25003. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  25004. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  25005. }
  25006. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25007. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  25008. }
  25009. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25010. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  25011. }
  25012. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  25013. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  25014. }
  25015. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  25016. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  25017. }
  25018. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  25019. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  25020. }
  25021. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  25022. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  25023. }
  25024. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  25025. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  25026. }
  25027. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25028. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  25029. }
  25030. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25031. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  25032. }
  25033. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  25034. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  25035. }
  25036. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  25037. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  25038. }
  25039. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  25040. return result;
  25041. };
  25042. /**
  25043. * Creates the vertexData of the Ribbon.
  25044. */
  25045. VertexData.CreateRibbon = function (options) {
  25046. var pathArray = options.pathArray;
  25047. var closeArray = options.closeArray || false;
  25048. var closePath = options.closePath || false;
  25049. var invertUV = options.invertUV || false;
  25050. var defaultOffset = Math.floor(pathArray[0].length / 2);
  25051. var offset = options.offset || defaultOffset;
  25052. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  25053. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25054. var customUV = options.uvs;
  25055. var customColors = options.colors;
  25056. var positions = [];
  25057. var indices = [];
  25058. var normals = [];
  25059. var uvs = [];
  25060. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  25061. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  25062. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  25063. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  25064. var minlg; // minimal length among all paths from pathArray
  25065. var lg = []; // array of path lengths : nb of vertex per path
  25066. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  25067. var p; // path iterator
  25068. var i; // point iterator
  25069. var j; // point iterator
  25070. // if single path in pathArray
  25071. if (pathArray.length < 2) {
  25072. var ar1 = [];
  25073. var ar2 = [];
  25074. for (i = 0; i < pathArray[0].length - offset; i++) {
  25075. ar1.push(pathArray[0][i]);
  25076. ar2.push(pathArray[0][i + offset]);
  25077. }
  25078. pathArray = [ar1, ar2];
  25079. }
  25080. // positions and horizontal distances (u)
  25081. var idc = 0;
  25082. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  25083. var path;
  25084. var l;
  25085. minlg = pathArray[0].length;
  25086. var vectlg;
  25087. var dist;
  25088. for (p = 0; p < pathArray.length; p++) {
  25089. uTotalDistance[p] = 0;
  25090. us[p] = [0];
  25091. path = pathArray[p];
  25092. l = path.length;
  25093. minlg = (minlg < l) ? minlg : l;
  25094. j = 0;
  25095. while (j < l) {
  25096. positions.push(path[j].x, path[j].y, path[j].z);
  25097. if (j > 0) {
  25098. vectlg = path[j].subtract(path[j - 1]).length();
  25099. dist = vectlg + uTotalDistance[p];
  25100. us[p].push(dist);
  25101. uTotalDistance[p] = dist;
  25102. }
  25103. j++;
  25104. }
  25105. if (closePath) {
  25106. j--;
  25107. positions.push(path[0].x, path[0].y, path[0].z);
  25108. vectlg = path[j].subtract(path[0]).length();
  25109. dist = vectlg + uTotalDistance[p];
  25110. us[p].push(dist);
  25111. uTotalDistance[p] = dist;
  25112. }
  25113. lg[p] = l + closePathCorr;
  25114. idx[p] = idc;
  25115. idc += (l + closePathCorr);
  25116. }
  25117. // vertical distances (v)
  25118. var path1;
  25119. var path2;
  25120. var vertex1;
  25121. var vertex2;
  25122. for (i = 0; i < minlg + closePathCorr; i++) {
  25123. vTotalDistance[i] = 0;
  25124. vs[i] = [0];
  25125. for (p = 0; p < pathArray.length - 1; p++) {
  25126. path1 = pathArray[p];
  25127. path2 = pathArray[p + 1];
  25128. if (i === minlg) {
  25129. vertex1 = path1[0];
  25130. vertex2 = path2[0];
  25131. }
  25132. else {
  25133. vertex1 = path1[i];
  25134. vertex2 = path2[i];
  25135. }
  25136. vectlg = vertex2.subtract(vertex1).length();
  25137. dist = vectlg + vTotalDistance[i];
  25138. vs[i].push(dist);
  25139. vTotalDistance[i] = dist;
  25140. }
  25141. if (closeArray) {
  25142. path1 = pathArray[p];
  25143. path2 = pathArray[0];
  25144. if (i === minlg) {
  25145. vertex2 = path2[0];
  25146. }
  25147. vectlg = vertex2.subtract(vertex1).length();
  25148. dist = vectlg + vTotalDistance[i];
  25149. vTotalDistance[i] = dist;
  25150. }
  25151. }
  25152. // uvs
  25153. var u;
  25154. var v;
  25155. if (customUV) {
  25156. for (p = 0; p < customUV.length; p++) {
  25157. uvs.push(customUV[p].x, customUV[p].y);
  25158. }
  25159. }
  25160. else {
  25161. for (p = 0; p < pathArray.length; p++) {
  25162. for (i = 0; i < minlg + closePathCorr; i++) {
  25163. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  25164. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  25165. if (invertUV) {
  25166. uvs.push(v, u);
  25167. }
  25168. else {
  25169. uvs.push(u, v);
  25170. }
  25171. }
  25172. }
  25173. }
  25174. // indices
  25175. p = 0; // path index
  25176. var pi = 0; // positions array index
  25177. var l1 = lg[p] - 1; // path1 length
  25178. var l2 = lg[p + 1] - 1; // path2 length
  25179. var min = (l1 < l2) ? l1 : l2; // current path stop index
  25180. var shft = idx[1] - idx[0]; // shift
  25181. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  25182. while (pi <= min && p < path1nb) {
  25183. // 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
  25184. indices.push(pi, pi + shft, pi + 1);
  25185. indices.push(pi + shft + 1, pi + 1, pi + shft);
  25186. pi += 1;
  25187. if (pi === min) {
  25188. p++;
  25189. if (p === lg.length - 1) {
  25190. shft = idx[0] - idx[p];
  25191. l1 = lg[p] - 1;
  25192. l2 = lg[0] - 1;
  25193. }
  25194. else {
  25195. shft = idx[p + 1] - idx[p];
  25196. l1 = lg[p] - 1;
  25197. l2 = lg[p + 1] - 1;
  25198. }
  25199. pi = idx[p];
  25200. min = (l1 < l2) ? l1 + pi : l2 + pi;
  25201. }
  25202. }
  25203. // normals
  25204. VertexData.ComputeNormals(positions, indices, normals);
  25205. if (closePath) {
  25206. var indexFirst = 0;
  25207. var indexLast = 0;
  25208. for (p = 0; p < pathArray.length; p++) {
  25209. indexFirst = idx[p] * 3;
  25210. if (p + 1 < pathArray.length) {
  25211. indexLast = (idx[p + 1] - 1) * 3;
  25212. }
  25213. else {
  25214. indexLast = normals.length - 3;
  25215. }
  25216. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  25217. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  25218. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  25219. normals[indexLast] = normals[indexFirst];
  25220. normals[indexLast + 1] = normals[indexFirst + 1];
  25221. normals[indexLast + 2] = normals[indexFirst + 2];
  25222. }
  25223. }
  25224. // sides
  25225. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25226. // Colors
  25227. if (customColors) {
  25228. var colors = new Float32Array(customColors.length * 4);
  25229. for (var c = 0; c < customColors.length; c++) {
  25230. colors[c * 4] = customColors[c].r;
  25231. colors[c * 4 + 1] = customColors[c].g;
  25232. colors[c * 4 + 2] = customColors[c].b;
  25233. colors[c * 4 + 3] = customColors[c].a;
  25234. }
  25235. }
  25236. // Result
  25237. var vertexData = new VertexData();
  25238. var positions32 = new Float32Array(positions);
  25239. var normals32 = new Float32Array(normals);
  25240. var uvs32 = new Float32Array(uvs);
  25241. vertexData.indices = indices;
  25242. vertexData.positions = positions32;
  25243. vertexData.normals = normals32;
  25244. vertexData.uvs = uvs32;
  25245. if (customColors) {
  25246. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  25247. }
  25248. if (closePath) {
  25249. vertexData._idx = idx;
  25250. }
  25251. return vertexData;
  25252. };
  25253. /**
  25254. * Creates the VertexData of the Box.
  25255. */
  25256. VertexData.CreateBox = function (options) {
  25257. var normalsSource = [
  25258. new BABYLON.Vector3(0, 0, 1),
  25259. new BABYLON.Vector3(0, 0, -1),
  25260. new BABYLON.Vector3(1, 0, 0),
  25261. new BABYLON.Vector3(-1, 0, 0),
  25262. new BABYLON.Vector3(0, 1, 0),
  25263. new BABYLON.Vector3(0, -1, 0)
  25264. ];
  25265. var indices = [];
  25266. var positions = [];
  25267. var normals = [];
  25268. var uvs = [];
  25269. var width = options.width || options.size || 1;
  25270. var height = options.height || options.size || 1;
  25271. var depth = options.depth || options.size || 1;
  25272. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25273. var faceUV = options.faceUV || new Array(6);
  25274. var faceColors = options.faceColors;
  25275. var colors = [];
  25276. // default face colors and UV if undefined
  25277. for (var f = 0; f < 6; f++) {
  25278. if (faceUV[f] === undefined) {
  25279. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25280. }
  25281. if (faceColors && faceColors[f] === undefined) {
  25282. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25283. }
  25284. }
  25285. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  25286. // Create each face in turn.
  25287. for (var index = 0; index < normalsSource.length; index++) {
  25288. var normal = normalsSource[index];
  25289. // Get two vectors perpendicular to the face normal and to each other.
  25290. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  25291. var side2 = BABYLON.Vector3.Cross(normal, side1);
  25292. // Six indices (two triangles) per face.
  25293. var verticesLength = positions.length / 3;
  25294. indices.push(verticesLength);
  25295. indices.push(verticesLength + 1);
  25296. indices.push(verticesLength + 2);
  25297. indices.push(verticesLength);
  25298. indices.push(verticesLength + 2);
  25299. indices.push(verticesLength + 3);
  25300. // Four vertices per face.
  25301. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  25302. positions.push(vertex.x, vertex.y, vertex.z);
  25303. normals.push(normal.x, normal.y, normal.z);
  25304. uvs.push(faceUV[index].z, faceUV[index].w);
  25305. if (faceColors) {
  25306. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25307. }
  25308. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  25309. positions.push(vertex.x, vertex.y, vertex.z);
  25310. normals.push(normal.x, normal.y, normal.z);
  25311. uvs.push(faceUV[index].x, faceUV[index].w);
  25312. if (faceColors) {
  25313. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25314. }
  25315. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  25316. positions.push(vertex.x, vertex.y, vertex.z);
  25317. normals.push(normal.x, normal.y, normal.z);
  25318. uvs.push(faceUV[index].x, faceUV[index].y);
  25319. if (faceColors) {
  25320. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25321. }
  25322. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  25323. positions.push(vertex.x, vertex.y, vertex.z);
  25324. normals.push(normal.x, normal.y, normal.z);
  25325. uvs.push(faceUV[index].z, faceUV[index].y);
  25326. if (faceColors) {
  25327. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  25328. }
  25329. }
  25330. // sides
  25331. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25332. // Result
  25333. var vertexData = new VertexData();
  25334. vertexData.indices = indices;
  25335. vertexData.positions = positions;
  25336. vertexData.normals = normals;
  25337. vertexData.uvs = uvs;
  25338. if (faceColors) {
  25339. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  25340. vertexData.colors = totalColors;
  25341. }
  25342. return vertexData;
  25343. };
  25344. /**
  25345. * Creates the VertexData of the Sphere.
  25346. */
  25347. VertexData.CreateSphere = function (options) {
  25348. var segments = options.segments || 32;
  25349. var diameterX = options.diameterX || options.diameter || 1;
  25350. var diameterY = options.diameterY || options.diameter || 1;
  25351. var diameterZ = options.diameterZ || options.diameter || 1;
  25352. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25353. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  25354. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25355. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  25356. var totalZRotationSteps = 2 + segments;
  25357. var totalYRotationSteps = 2 * totalZRotationSteps;
  25358. var indices = [];
  25359. var positions = [];
  25360. var normals = [];
  25361. var uvs = [];
  25362. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  25363. var normalizedZ = zRotationStep / totalZRotationSteps;
  25364. var angleZ = normalizedZ * Math.PI * slice;
  25365. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  25366. var normalizedY = yRotationStep / totalYRotationSteps;
  25367. var angleY = normalizedY * Math.PI * 2 * arc;
  25368. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  25369. var rotationY = BABYLON.Matrix.RotationY(angleY);
  25370. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  25371. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  25372. var vertex = complete.multiply(radius);
  25373. var normal = complete.divide(radius).normalize();
  25374. positions.push(vertex.x, vertex.y, vertex.z);
  25375. normals.push(normal.x, normal.y, normal.z);
  25376. uvs.push(normalizedY, normalizedZ);
  25377. }
  25378. if (zRotationStep > 0) {
  25379. var verticesCount = positions.length / 3;
  25380. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  25381. indices.push((firstIndex));
  25382. indices.push((firstIndex + 1));
  25383. indices.push(firstIndex + totalYRotationSteps + 1);
  25384. indices.push((firstIndex + totalYRotationSteps + 1));
  25385. indices.push((firstIndex + 1));
  25386. indices.push((firstIndex + totalYRotationSteps + 2));
  25387. }
  25388. }
  25389. }
  25390. // Sides
  25391. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25392. // Result
  25393. var vertexData = new VertexData();
  25394. vertexData.indices = indices;
  25395. vertexData.positions = positions;
  25396. vertexData.normals = normals;
  25397. vertexData.uvs = uvs;
  25398. return vertexData;
  25399. };
  25400. /**
  25401. * Creates the VertexData of the Cylinder or Cone.
  25402. */
  25403. VertexData.CreateCylinder = function (options) {
  25404. var height = options.height || 2;
  25405. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  25406. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  25407. var tessellation = options.tessellation || 24;
  25408. var subdivisions = options.subdivisions || 1;
  25409. var hasRings = options.hasRings;
  25410. var enclose = options.enclose;
  25411. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25412. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25413. var faceUV = options.faceUV || new Array(3);
  25414. var faceColors = options.faceColors;
  25415. // default face colors and UV if undefined
  25416. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  25417. var ringNb = (hasRings) ? subdivisions : 1;
  25418. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  25419. var f;
  25420. for (f = 0; f < surfaceNb; f++) {
  25421. if (faceColors && faceColors[f] === undefined) {
  25422. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25423. }
  25424. }
  25425. for (f = 0; f < surfaceNb; f++) {
  25426. if (faceUV && faceUV[f] === undefined) {
  25427. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25428. }
  25429. }
  25430. var indices = [];
  25431. var positions = [];
  25432. var normals = [];
  25433. var uvs = [];
  25434. var colors = [];
  25435. var angle_step = Math.PI * 2 * arc / tessellation;
  25436. var angle;
  25437. var h;
  25438. var radius;
  25439. var tan = (diameterBottom - diameterTop) / 2 / height;
  25440. var ringVertex = BABYLON.Vector3.Zero();
  25441. var ringNormal = BABYLON.Vector3.Zero();
  25442. var ringFirstVertex = BABYLON.Vector3.Zero();
  25443. var ringFirstNormal = BABYLON.Vector3.Zero();
  25444. var quadNormal = BABYLON.Vector3.Zero();
  25445. var Y = BABYLON.Axis.Y;
  25446. // positions, normals, uvs
  25447. var i;
  25448. var j;
  25449. var r;
  25450. var ringIdx = 1;
  25451. var s = 1; // surface index
  25452. var cs = 0;
  25453. var v = 0;
  25454. for (i = 0; i <= subdivisions; i++) {
  25455. h = i / subdivisions;
  25456. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  25457. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  25458. for (r = 0; r < ringIdx; r++) {
  25459. if (hasRings) {
  25460. s += r;
  25461. }
  25462. if (enclose) {
  25463. s += 2 * r;
  25464. }
  25465. for (j = 0; j <= tessellation; j++) {
  25466. angle = j * angle_step;
  25467. // position
  25468. ringVertex.x = Math.cos(-angle) * radius;
  25469. ringVertex.y = -height / 2 + h * height;
  25470. ringVertex.z = Math.sin(-angle) * radius;
  25471. // normal
  25472. if (diameterTop === 0 && i === subdivisions) {
  25473. // if no top cap, reuse former normals
  25474. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  25475. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  25476. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  25477. }
  25478. else {
  25479. ringNormal.x = ringVertex.x;
  25480. ringNormal.z = ringVertex.z;
  25481. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  25482. ringNormal.normalize();
  25483. }
  25484. // keep first ring vertex values for enclose
  25485. if (j === 0) {
  25486. ringFirstVertex.copyFrom(ringVertex);
  25487. ringFirstNormal.copyFrom(ringNormal);
  25488. }
  25489. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25490. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  25491. if (hasRings) {
  25492. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  25493. }
  25494. else {
  25495. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  25496. }
  25497. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  25498. if (faceColors) {
  25499. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  25500. }
  25501. }
  25502. // if enclose, add four vertices and their dedicated normals
  25503. if (arc !== 1 && enclose) {
  25504. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  25505. positions.push(0, ringVertex.y, 0);
  25506. positions.push(0, ringVertex.y, 0);
  25507. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  25508. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  25509. quadNormal.normalize();
  25510. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25511. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  25512. quadNormal.normalize();
  25513. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  25514. if (hasRings) {
  25515. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  25516. }
  25517. else {
  25518. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  25519. }
  25520. uvs.push(faceUV[s + 1].x, v);
  25521. uvs.push(faceUV[s + 1].z, v);
  25522. if (hasRings) {
  25523. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  25524. }
  25525. else {
  25526. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  25527. }
  25528. uvs.push(faceUV[s + 2].x, v);
  25529. uvs.push(faceUV[s + 2].z, v);
  25530. if (faceColors) {
  25531. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25532. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  25533. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25534. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  25535. }
  25536. }
  25537. if (cs !== s) {
  25538. cs = s;
  25539. }
  25540. }
  25541. }
  25542. // indices
  25543. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  25544. var s;
  25545. i = 0;
  25546. for (s = 0; s < subdivisions; s++) {
  25547. for (j = 0; j < tessellation; j++) {
  25548. var i0 = i * (e + 1) + j;
  25549. var i1 = (i + 1) * (e + 1) + j;
  25550. var i2 = i * (e + 1) + (j + 1);
  25551. var i3 = (i + 1) * (e + 1) + (j + 1);
  25552. indices.push(i0, i1, i2);
  25553. indices.push(i3, i2, i1);
  25554. }
  25555. if (arc !== 1 && enclose) {
  25556. indices.push(i0 + 2, i1 + 2, i2 + 2);
  25557. indices.push(i3 + 2, i2 + 2, i1 + 2);
  25558. indices.push(i0 + 4, i1 + 4, i2 + 4);
  25559. indices.push(i3 + 4, i2 + 4, i1 + 4);
  25560. }
  25561. i = (hasRings) ? (i + 2) : (i + 1);
  25562. }
  25563. // Caps
  25564. var createCylinderCap = function (isTop) {
  25565. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  25566. if (radius === 0) {
  25567. return;
  25568. }
  25569. // Cap positions, normals & uvs
  25570. var angle;
  25571. var circleVector;
  25572. var i;
  25573. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  25574. var c;
  25575. if (faceColors) {
  25576. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  25577. }
  25578. // cap center
  25579. var vbase = positions.length / 3;
  25580. var offset = isTop ? height / 2 : -height / 2;
  25581. var center = new BABYLON.Vector3(0, offset, 0);
  25582. positions.push(center.x, center.y, center.z);
  25583. normals.push(0, isTop ? 1 : -1, 0);
  25584. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  25585. if (faceColors) {
  25586. colors.push(c.r, c.g, c.b, c.a);
  25587. }
  25588. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  25589. for (i = 0; i <= tessellation; i++) {
  25590. angle = Math.PI * 2 * i * arc / tessellation;
  25591. var cos = Math.cos(-angle);
  25592. var sin = Math.sin(-angle);
  25593. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  25594. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  25595. positions.push(circleVector.x, circleVector.y, circleVector.z);
  25596. normals.push(0, isTop ? 1 : -1, 0);
  25597. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  25598. if (faceColors) {
  25599. colors.push(c.r, c.g, c.b, c.a);
  25600. }
  25601. }
  25602. // Cap indices
  25603. for (i = 0; i < tessellation; i++) {
  25604. if (!isTop) {
  25605. indices.push(vbase);
  25606. indices.push(vbase + (i + 1));
  25607. indices.push(vbase + (i + 2));
  25608. }
  25609. else {
  25610. indices.push(vbase);
  25611. indices.push(vbase + (i + 2));
  25612. indices.push(vbase + (i + 1));
  25613. }
  25614. }
  25615. };
  25616. // add caps to geometry
  25617. createCylinderCap(false);
  25618. createCylinderCap(true);
  25619. // Sides
  25620. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25621. var vertexData = new VertexData();
  25622. vertexData.indices = indices;
  25623. vertexData.positions = positions;
  25624. vertexData.normals = normals;
  25625. vertexData.uvs = uvs;
  25626. if (faceColors) {
  25627. vertexData.colors = colors;
  25628. }
  25629. return vertexData;
  25630. };
  25631. /**
  25632. * Creates the VertexData of the Torus.
  25633. */
  25634. VertexData.CreateTorus = function (options) {
  25635. var indices = [];
  25636. var positions = [];
  25637. var normals = [];
  25638. var uvs = [];
  25639. var diameter = options.diameter || 1;
  25640. var thickness = options.thickness || 0.5;
  25641. var tessellation = options.tessellation || 16;
  25642. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25643. var stride = tessellation + 1;
  25644. for (var i = 0; i <= tessellation; i++) {
  25645. var u = i / tessellation;
  25646. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  25647. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  25648. for (var j = 0; j <= tessellation; j++) {
  25649. var v = 1 - j / tessellation;
  25650. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  25651. var dx = Math.cos(innerAngle);
  25652. var dy = Math.sin(innerAngle);
  25653. // Create a vertex.
  25654. var normal = new BABYLON.Vector3(dx, dy, 0);
  25655. var position = normal.scale(thickness / 2);
  25656. var textureCoordinate = new BABYLON.Vector2(u, v);
  25657. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  25658. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  25659. positions.push(position.x, position.y, position.z);
  25660. normals.push(normal.x, normal.y, normal.z);
  25661. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25662. // And create indices for two triangles.
  25663. var nextI = (i + 1) % stride;
  25664. var nextJ = (j + 1) % stride;
  25665. indices.push(i * stride + j);
  25666. indices.push(i * stride + nextJ);
  25667. indices.push(nextI * stride + j);
  25668. indices.push(i * stride + nextJ);
  25669. indices.push(nextI * stride + nextJ);
  25670. indices.push(nextI * stride + j);
  25671. }
  25672. }
  25673. // Sides
  25674. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25675. // Result
  25676. var vertexData = new VertexData();
  25677. vertexData.indices = indices;
  25678. vertexData.positions = positions;
  25679. vertexData.normals = normals;
  25680. vertexData.uvs = uvs;
  25681. return vertexData;
  25682. };
  25683. /**
  25684. * Creates the VertexData of the LineSystem.
  25685. */
  25686. VertexData.CreateLineSystem = function (options) {
  25687. var indices = [];
  25688. var positions = [];
  25689. var lines = options.lines;
  25690. var idx = 0;
  25691. for (var l = 0; l < lines.length; l++) {
  25692. var points = lines[l];
  25693. for (var index = 0; index < points.length; index++) {
  25694. positions.push(points[index].x, points[index].y, points[index].z);
  25695. if (index > 0) {
  25696. indices.push(idx - 1);
  25697. indices.push(idx);
  25698. }
  25699. idx++;
  25700. }
  25701. }
  25702. var vertexData = new VertexData();
  25703. vertexData.indices = indices;
  25704. vertexData.positions = positions;
  25705. return vertexData;
  25706. };
  25707. /**
  25708. * Create the VertexData of the DashedLines.
  25709. */
  25710. VertexData.CreateDashedLines = function (options) {
  25711. var dashSize = options.dashSize || 3;
  25712. var gapSize = options.gapSize || 1;
  25713. var dashNb = options.dashNb || 200;
  25714. var points = options.points;
  25715. var positions = new Array();
  25716. var indices = new Array();
  25717. var curvect = BABYLON.Vector3.Zero();
  25718. var lg = 0;
  25719. var nb = 0;
  25720. var shft = 0;
  25721. var dashshft = 0;
  25722. var curshft = 0;
  25723. var idx = 0;
  25724. var i = 0;
  25725. for (i = 0; i < points.length - 1; i++) {
  25726. points[i + 1].subtractToRef(points[i], curvect);
  25727. lg += curvect.length();
  25728. }
  25729. shft = lg / dashNb;
  25730. dashshft = dashSize * shft / (dashSize + gapSize);
  25731. for (i = 0; i < points.length - 1; i++) {
  25732. points[i + 1].subtractToRef(points[i], curvect);
  25733. nb = Math.floor(curvect.length() / shft);
  25734. curvect.normalize();
  25735. for (var j = 0; j < nb; j++) {
  25736. curshft = shft * j;
  25737. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  25738. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  25739. indices.push(idx, idx + 1);
  25740. idx += 2;
  25741. }
  25742. }
  25743. // Result
  25744. var vertexData = new VertexData();
  25745. vertexData.positions = positions;
  25746. vertexData.indices = indices;
  25747. return vertexData;
  25748. };
  25749. /**
  25750. * Creates the VertexData of the Ground.
  25751. */
  25752. VertexData.CreateGround = function (options) {
  25753. var indices = [];
  25754. var positions = [];
  25755. var normals = [];
  25756. var uvs = [];
  25757. var row, col;
  25758. var width = options.width || 1;
  25759. var height = options.height || 1;
  25760. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  25761. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  25762. for (row = 0; row <= subdivisionsY; row++) {
  25763. for (col = 0; col <= subdivisionsX; col++) {
  25764. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  25765. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25766. positions.push(position.x, position.y, position.z);
  25767. normals.push(normal.x, normal.y, normal.z);
  25768. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  25769. }
  25770. }
  25771. for (row = 0; row < subdivisionsY; row++) {
  25772. for (col = 0; col < subdivisionsX; col++) {
  25773. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  25774. indices.push(col + 1 + row * (subdivisionsX + 1));
  25775. indices.push(col + row * (subdivisionsX + 1));
  25776. indices.push(col + (row + 1) * (subdivisionsX + 1));
  25777. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  25778. indices.push(col + row * (subdivisionsX + 1));
  25779. }
  25780. }
  25781. // Result
  25782. var vertexData = new VertexData();
  25783. vertexData.indices = indices;
  25784. vertexData.positions = positions;
  25785. vertexData.normals = normals;
  25786. vertexData.uvs = uvs;
  25787. return vertexData;
  25788. };
  25789. /**
  25790. * Creates the VertexData of the TiledGround.
  25791. */
  25792. VertexData.CreateTiledGround = function (options) {
  25793. var xmin = options.xmin || -1.0;
  25794. var zmin = options.zmin || -1.0;
  25795. var xmax = options.xmax || 1.0;
  25796. var zmax = options.zmax || 1.0;
  25797. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  25798. var precision = options.precision || { w: 1, h: 1 };
  25799. var indices = [];
  25800. var positions = [];
  25801. var normals = [];
  25802. var uvs = [];
  25803. var row, col, tileRow, tileCol;
  25804. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  25805. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  25806. precision.w = (precision.w < 1) ? 1 : precision.w;
  25807. precision.h = (precision.h < 1) ? 1 : precision.h;
  25808. var tileSize = {
  25809. 'w': (xmax - xmin) / subdivisions.w,
  25810. 'h': (zmax - zmin) / subdivisions.h
  25811. };
  25812. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  25813. // Indices
  25814. var base = positions.length / 3;
  25815. var rowLength = precision.w + 1;
  25816. for (row = 0; row < precision.h; row++) {
  25817. for (col = 0; col < precision.w; col++) {
  25818. var square = [
  25819. base + col + row * rowLength,
  25820. base + (col + 1) + row * rowLength,
  25821. base + (col + 1) + (row + 1) * rowLength,
  25822. base + col + (row + 1) * rowLength
  25823. ];
  25824. indices.push(square[1]);
  25825. indices.push(square[2]);
  25826. indices.push(square[3]);
  25827. indices.push(square[0]);
  25828. indices.push(square[1]);
  25829. indices.push(square[3]);
  25830. }
  25831. }
  25832. // Position, normals and uvs
  25833. var position = BABYLON.Vector3.Zero();
  25834. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25835. for (row = 0; row <= precision.h; row++) {
  25836. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  25837. for (col = 0; col <= precision.w; col++) {
  25838. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  25839. position.y = 0;
  25840. positions.push(position.x, position.y, position.z);
  25841. normals.push(normal.x, normal.y, normal.z);
  25842. uvs.push(col / precision.w, row / precision.h);
  25843. }
  25844. }
  25845. }
  25846. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  25847. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  25848. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  25849. }
  25850. }
  25851. // Result
  25852. var vertexData = new VertexData();
  25853. vertexData.indices = indices;
  25854. vertexData.positions = positions;
  25855. vertexData.normals = normals;
  25856. vertexData.uvs = uvs;
  25857. return vertexData;
  25858. };
  25859. /**
  25860. * Creates the VertexData of the Ground designed from a heightmap.
  25861. */
  25862. VertexData.CreateGroundFromHeightMap = function (options) {
  25863. var indices = [];
  25864. var positions = [];
  25865. var normals = [];
  25866. var uvs = [];
  25867. var row, col;
  25868. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  25869. // Vertices
  25870. for (row = 0; row <= options.subdivisions; row++) {
  25871. for (col = 0; col <= options.subdivisions; col++) {
  25872. 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));
  25873. // Compute height
  25874. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  25875. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  25876. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  25877. var r = options.buffer[pos] / 255.0;
  25878. var g = options.buffer[pos + 1] / 255.0;
  25879. var b = options.buffer[pos + 2] / 255.0;
  25880. var gradient = r * filter.r + g * filter.g + b * filter.b;
  25881. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  25882. // Add vertex
  25883. positions.push(position.x, position.y, position.z);
  25884. normals.push(0, 0, 0);
  25885. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  25886. }
  25887. }
  25888. // Indices
  25889. for (row = 0; row < options.subdivisions; row++) {
  25890. for (col = 0; col < options.subdivisions; col++) {
  25891. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25892. indices.push(col + 1 + row * (options.subdivisions + 1));
  25893. indices.push(col + row * (options.subdivisions + 1));
  25894. indices.push(col + (row + 1) * (options.subdivisions + 1));
  25895. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25896. indices.push(col + row * (options.subdivisions + 1));
  25897. }
  25898. }
  25899. // Normals
  25900. VertexData.ComputeNormals(positions, indices, normals);
  25901. // Result
  25902. var vertexData = new VertexData();
  25903. vertexData.indices = indices;
  25904. vertexData.positions = positions;
  25905. vertexData.normals = normals;
  25906. vertexData.uvs = uvs;
  25907. return vertexData;
  25908. };
  25909. /**
  25910. * Creates the VertexData of the Plane.
  25911. */
  25912. VertexData.CreatePlane = function (options) {
  25913. var indices = [];
  25914. var positions = [];
  25915. var normals = [];
  25916. var uvs = [];
  25917. var width = options.width || options.size || 1;
  25918. var height = options.height || options.size || 1;
  25919. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25920. // Vertices
  25921. var halfWidth = width / 2.0;
  25922. var halfHeight = height / 2.0;
  25923. positions.push(-halfWidth, -halfHeight, 0);
  25924. normals.push(0, 0, -1.0);
  25925. uvs.push(0.0, 0.0);
  25926. positions.push(halfWidth, -halfHeight, 0);
  25927. normals.push(0, 0, -1.0);
  25928. uvs.push(1.0, 0.0);
  25929. positions.push(halfWidth, halfHeight, 0);
  25930. normals.push(0, 0, -1.0);
  25931. uvs.push(1.0, 1.0);
  25932. positions.push(-halfWidth, halfHeight, 0);
  25933. normals.push(0, 0, -1.0);
  25934. uvs.push(0.0, 1.0);
  25935. // Indices
  25936. indices.push(0);
  25937. indices.push(1);
  25938. indices.push(2);
  25939. indices.push(0);
  25940. indices.push(2);
  25941. indices.push(3);
  25942. // Sides
  25943. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25944. // Result
  25945. var vertexData = new VertexData();
  25946. vertexData.indices = indices;
  25947. vertexData.positions = positions;
  25948. vertexData.normals = normals;
  25949. vertexData.uvs = uvs;
  25950. return vertexData;
  25951. };
  25952. /**
  25953. * Creates the VertexData of the Disc or regular Polygon.
  25954. */
  25955. VertexData.CreateDisc = function (options) {
  25956. var positions = [];
  25957. var indices = [];
  25958. var normals = [];
  25959. var uvs = [];
  25960. var radius = options.radius || 0.5;
  25961. var tessellation = options.tessellation || 64;
  25962. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25963. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25964. // positions and uvs
  25965. positions.push(0, 0, 0); // disc center first
  25966. uvs.push(0.5, 0.5);
  25967. var theta = Math.PI * 2 * arc;
  25968. var step = theta / tessellation;
  25969. for (var a = 0; a < theta; a += step) {
  25970. var x = Math.cos(a);
  25971. var y = Math.sin(a);
  25972. var u = (x + 1) / 2;
  25973. var v = (1 - y) / 2;
  25974. positions.push(radius * x, radius * y, 0);
  25975. uvs.push(u, v);
  25976. }
  25977. if (arc === 1) {
  25978. positions.push(positions[3], positions[4], positions[5]); // close the circle
  25979. uvs.push(uvs[2], uvs[3]);
  25980. }
  25981. //indices
  25982. var vertexNb = positions.length / 3;
  25983. for (var i = 1; i < vertexNb - 1; i++) {
  25984. indices.push(i + 1, 0, i);
  25985. }
  25986. // result
  25987. VertexData.ComputeNormals(positions, indices, normals);
  25988. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  25989. var vertexData = new VertexData();
  25990. vertexData.indices = indices;
  25991. vertexData.positions = positions;
  25992. vertexData.normals = normals;
  25993. vertexData.uvs = uvs;
  25994. return vertexData;
  25995. };
  25996. /**
  25997. * Re-creates the VertexData of the Polygon for sideOrientation.
  25998. */
  25999. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  26000. var faceUV = fUV || new Array(3);
  26001. var faceColors = fColors;
  26002. var colors = [];
  26003. // default face colors and UV if undefined
  26004. for (var f = 0; f < 3; f++) {
  26005. if (faceUV[f] === undefined) {
  26006. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26007. }
  26008. if (faceColors && faceColors[f] === undefined) {
  26009. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26010. }
  26011. }
  26012. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26013. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26014. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26015. var indices = polygon.getIndices();
  26016. // set face colours and textures
  26017. var idx = 0;
  26018. var face = 0;
  26019. for (var index = 0; index < normals.length; index += 3) {
  26020. //Edge Face no. 1
  26021. if (Math.abs(normals[index + 1]) == 0) {
  26022. face = 1;
  26023. }
  26024. //Top Face no. 0
  26025. if (normals[index + 1] == 1) {
  26026. face = 0;
  26027. }
  26028. //Bottom Face no. 2
  26029. if (normals[index + 1] == -1) {
  26030. face = 2;
  26031. }
  26032. idx = index / 3;
  26033. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  26034. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  26035. if (faceColors) {
  26036. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  26037. }
  26038. }
  26039. // sides
  26040. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  26041. // Result
  26042. var vertexData = new VertexData();
  26043. vertexData.indices = indices;
  26044. vertexData.positions = positions;
  26045. vertexData.normals = normals;
  26046. vertexData.uvs = uvs;
  26047. if (faceColors) {
  26048. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26049. vertexData.colors = totalColors;
  26050. }
  26051. return vertexData;
  26052. };
  26053. /**
  26054. * Creates the VertexData of the IcoSphere.
  26055. */
  26056. VertexData.CreateIcoSphere = function (options) {
  26057. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26058. var radius = options.radius || 1;
  26059. var flat = (options.flat === undefined) ? true : options.flat;
  26060. var subdivisions = options.subdivisions || 4;
  26061. var radiusX = options.radiusX || radius;
  26062. var radiusY = options.radiusY || radius;
  26063. var radiusZ = options.radiusZ || radius;
  26064. var t = (1 + Math.sqrt(5)) / 2;
  26065. // 12 vertex x,y,z
  26066. var ico_vertices = [
  26067. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  26068. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  26069. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  26070. ];
  26071. // index of 3 vertex makes a face of icopshere
  26072. var ico_indices = [
  26073. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  26074. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  26075. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  26076. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  26077. ];
  26078. // vertex for uv have aliased position, not for UV
  26079. var vertices_unalias_id = [
  26080. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  26081. // vertex alias
  26082. 0,
  26083. 2,
  26084. 3,
  26085. 3,
  26086. 3,
  26087. 4,
  26088. 7,
  26089. 8,
  26090. 9,
  26091. 9,
  26092. 10,
  26093. 11 // 23: B + 12
  26094. ];
  26095. // uv as integer step (not pixels !)
  26096. var ico_vertexuv = [
  26097. 5, 1, 3, 1, 6, 4, 0, 0,
  26098. 5, 3, 4, 2, 2, 2, 4, 0,
  26099. 2, 0, 1, 1, 6, 0, 6, 2,
  26100. // vertex alias (for same vertex on different faces)
  26101. 0, 4,
  26102. 3, 3,
  26103. 4, 4,
  26104. 3, 1,
  26105. 4, 2,
  26106. 4, 4,
  26107. 0, 2,
  26108. 1, 1,
  26109. 2, 2,
  26110. 3, 3,
  26111. 1, 3,
  26112. 2, 4 // 23: B + 12
  26113. ];
  26114. // Vertices[0, 1, ...9, A, B] : position on UV plane
  26115. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  26116. // First island of uv mapping
  26117. // v = 4h 3+ 2
  26118. // v = 3h 9+ 4
  26119. // v = 2h 9+ 5 B
  26120. // v = 1h 9 1 0
  26121. // v = 0h 3 8 7 A
  26122. // u = 0 1 2 3 4 5 6 *a
  26123. // Second island of uv mapping
  26124. // v = 4h 0+ B+ 4+
  26125. // v = 3h A+ 2+
  26126. // v = 2h 7+ 6 3+
  26127. // v = 1h 8+ 3+
  26128. // v = 0h
  26129. // u = 0 1 2 3 4 5 6 *a
  26130. // Face layout on texture UV mapping
  26131. // ============
  26132. // \ 4 /\ 16 / ======
  26133. // \ / \ / /\ 11 /
  26134. // \/ 7 \/ / \ /
  26135. // ======= / 10 \/
  26136. // /\ 17 /\ =======
  26137. // / \ / \ \ 15 /\
  26138. // / 8 \/ 12 \ \ / \
  26139. // ============ \/ 6 \
  26140. // \ 18 /\ ============
  26141. // \ / \ \ 5 /\ 0 /
  26142. // \/ 13 \ \ / \ /
  26143. // ======= \/ 1 \/
  26144. // =============
  26145. // /\ 19 /\ 2 /\
  26146. // / \ / \ / \
  26147. // / 14 \/ 9 \/ 3 \
  26148. // ===================
  26149. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  26150. var ustep = 138 / 1024;
  26151. var vstep = 239 / 1024;
  26152. var uoffset = 60 / 1024;
  26153. var voffset = 26 / 1024;
  26154. // Second island should have margin, not to touch the first island
  26155. // avoid any borderline artefact in pixel rounding
  26156. var island_u_offset = -40 / 1024;
  26157. var island_v_offset = +20 / 1024;
  26158. // face is either island 0 or 1 :
  26159. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  26160. var island = [
  26161. 0, 0, 0, 0, 1,
  26162. 0, 0, 1, 1, 0,
  26163. 0, 0, 1, 1, 0,
  26164. 0, 1, 1, 1, 0 // 15 - 19
  26165. ];
  26166. var indices = [];
  26167. var positions = [];
  26168. var normals = [];
  26169. var uvs = [];
  26170. var current_indice = 0;
  26171. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  26172. var face_vertex_pos = new Array(3);
  26173. var face_vertex_uv = new Array(3);
  26174. var v012;
  26175. for (v012 = 0; v012 < 3; v012++) {
  26176. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  26177. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  26178. }
  26179. // create all with normals
  26180. for (var face = 0; face < 20; face++) {
  26181. // 3 vertex per face
  26182. for (v012 = 0; v012 < 3; v012++) {
  26183. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  26184. var v_id = ico_indices[3 * face + v012];
  26185. // vertex have 3D position (x,y,z)
  26186. 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]);
  26187. // Normalize to get normal, then scale to radius
  26188. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  26189. // uv Coordinates from vertex ID
  26190. 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);
  26191. }
  26192. // Subdivide the face (interpolate pos, norm, uv)
  26193. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  26194. // - norm is linear interpolation of vertex corner normal
  26195. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  26196. // - uv is linear interpolation
  26197. //
  26198. // Topology is as below for sub-divide by 2
  26199. // vertex shown as v0,v1,v2
  26200. // interp index is i1 to progress in range [v0,v1[
  26201. // interp index is i2 to progress in range [v0,v2[
  26202. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  26203. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  26204. //
  26205. //
  26206. // i2 v2
  26207. // ^ ^
  26208. // / / \
  26209. // / / \
  26210. // / / \
  26211. // / / (0,1) \
  26212. // / #---------\
  26213. // / / \ (0,0)'/ \
  26214. // / / \ / \
  26215. // / / \ / \
  26216. // / / (0,0) \ / (1,0) \
  26217. // / #---------#---------\
  26218. // v0 v1
  26219. //
  26220. // --------------------> i1
  26221. //
  26222. // interp of (i1,i2):
  26223. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  26224. // along i1 : lerp(x0,x1, i1/(S-i2))
  26225. //
  26226. // centroid of triangle is needed to get help normal computation
  26227. // (c1,c2) are used for centroid location
  26228. var interp_vertex = function (i1, i2, c1, c2) {
  26229. // vertex is interpolated from
  26230. // - face_vertex_pos[0..2]
  26231. // - face_vertex_uv[0..2]
  26232. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  26233. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  26234. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  26235. pos_interp.normalize();
  26236. var vertex_normal;
  26237. if (flat) {
  26238. // in flat mode, recalculate normal as face centroid normal
  26239. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  26240. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  26241. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  26242. }
  26243. else {
  26244. // in smooth mode, recalculate normal from each single vertex position
  26245. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  26246. }
  26247. // Vertex normal need correction due to X,Y,Z radius scaling
  26248. vertex_normal.x /= radiusX;
  26249. vertex_normal.y /= radiusY;
  26250. vertex_normal.z /= radiusZ;
  26251. vertex_normal.normalize();
  26252. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  26253. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  26254. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  26255. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  26256. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  26257. uvs.push(uv_interp.x, uv_interp.y);
  26258. // push each vertex has member of a face
  26259. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  26260. indices.push(current_indice);
  26261. current_indice++;
  26262. };
  26263. for (var i2 = 0; i2 < subdivisions; i2++) {
  26264. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  26265. // face : (i1,i2) for /\ :
  26266. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  26267. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26268. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26269. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  26270. if (i1 + i2 + 1 < subdivisions) {
  26271. // face : (i1,i2)' for \/ :
  26272. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  26273. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26274. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26275. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  26276. }
  26277. }
  26278. }
  26279. }
  26280. // Sides
  26281. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26282. // Result
  26283. var vertexData = new VertexData();
  26284. vertexData.indices = indices;
  26285. vertexData.positions = positions;
  26286. vertexData.normals = normals;
  26287. vertexData.uvs = uvs;
  26288. return vertexData;
  26289. };
  26290. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  26291. /**
  26292. * Creates the VertexData of the Polyhedron.
  26293. */
  26294. VertexData.CreatePolyhedron = function (options) {
  26295. // provided polyhedron types :
  26296. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  26297. // 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)
  26298. var polyhedra = [];
  26299. 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]] };
  26300. 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]] };
  26301. polyhedra[2] = {
  26302. 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]],
  26303. 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]]
  26304. };
  26305. polyhedra[3] = {
  26306. 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]],
  26307. 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]]
  26308. };
  26309. polyhedra[4] = {
  26310. 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]],
  26311. 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]]
  26312. };
  26313. 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]] };
  26314. 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]] };
  26315. 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]] };
  26316. 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]] };
  26317. 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]] };
  26318. 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]] };
  26319. 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]] };
  26320. 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]] };
  26321. 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]] };
  26322. polyhedra[14] = {
  26323. 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]],
  26324. 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]]
  26325. };
  26326. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  26327. var size = options.size;
  26328. var sizeX = options.sizeX || size || 1;
  26329. var sizeY = options.sizeY || size || 1;
  26330. var sizeZ = options.sizeZ || size || 1;
  26331. var data = options.custom || polyhedra[type];
  26332. var nbfaces = data.face.length;
  26333. var faceUV = options.faceUV || new Array(nbfaces);
  26334. var faceColors = options.faceColors;
  26335. var flat = (options.flat === undefined) ? true : options.flat;
  26336. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26337. var positions = [];
  26338. var indices = [];
  26339. var normals = [];
  26340. var uvs = [];
  26341. var colors = [];
  26342. var index = 0;
  26343. var faceIdx = 0; // face cursor in the array "indexes"
  26344. var indexes = [];
  26345. var i = 0;
  26346. var f = 0;
  26347. var u, v, ang, x, y, tmp;
  26348. // default face colors and UV if undefined
  26349. if (flat) {
  26350. for (f = 0; f < nbfaces; f++) {
  26351. if (faceColors && faceColors[f] === undefined) {
  26352. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26353. }
  26354. if (faceUV && faceUV[f] === undefined) {
  26355. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26356. }
  26357. }
  26358. }
  26359. if (!flat) {
  26360. for (i = 0; i < data.vertex.length; i++) {
  26361. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  26362. uvs.push(0, 0);
  26363. }
  26364. for (f = 0; f < nbfaces; f++) {
  26365. for (i = 0; i < data.face[f].length - 2; i++) {
  26366. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  26367. }
  26368. }
  26369. }
  26370. else {
  26371. for (f = 0; f < nbfaces; f++) {
  26372. var fl = data.face[f].length; // number of vertices of the current face
  26373. ang = 2 * Math.PI / fl;
  26374. x = 0.5 * Math.tan(ang / 2);
  26375. y = 0.5;
  26376. // positions, uvs, colors
  26377. for (i = 0; i < fl; i++) {
  26378. // positions
  26379. 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);
  26380. indexes.push(index);
  26381. index++;
  26382. // uvs
  26383. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  26384. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  26385. uvs.push(u, v);
  26386. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  26387. y = x * Math.sin(ang) + y * Math.cos(ang);
  26388. x = tmp;
  26389. // colors
  26390. if (faceColors) {
  26391. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  26392. }
  26393. }
  26394. // indices from indexes
  26395. for (i = 0; i < fl - 2; i++) {
  26396. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  26397. }
  26398. faceIdx += fl;
  26399. }
  26400. }
  26401. VertexData.ComputeNormals(positions, indices, normals);
  26402. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26403. var vertexData = new VertexData();
  26404. vertexData.positions = positions;
  26405. vertexData.indices = indices;
  26406. vertexData.normals = normals;
  26407. vertexData.uvs = uvs;
  26408. if (faceColors && flat) {
  26409. vertexData.colors = colors;
  26410. }
  26411. return vertexData;
  26412. };
  26413. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  26414. /**
  26415. * Creates the VertexData of the Torus Knot.
  26416. */
  26417. VertexData.CreateTorusKnot = function (options) {
  26418. var indices = [];
  26419. var positions = [];
  26420. var normals = [];
  26421. var uvs = [];
  26422. var radius = options.radius || 2;
  26423. var tube = options.tube || 0.5;
  26424. var radialSegments = options.radialSegments || 32;
  26425. var tubularSegments = options.tubularSegments || 32;
  26426. var p = options.p || 2;
  26427. var q = options.q || 3;
  26428. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26429. // Helper
  26430. var getPos = function (angle) {
  26431. var cu = Math.cos(angle);
  26432. var su = Math.sin(angle);
  26433. var quOverP = q / p * angle;
  26434. var cs = Math.cos(quOverP);
  26435. var tx = radius * (2 + cs) * 0.5 * cu;
  26436. var ty = radius * (2 + cs) * su * 0.5;
  26437. var tz = radius * Math.sin(quOverP) * 0.5;
  26438. return new BABYLON.Vector3(tx, ty, tz);
  26439. };
  26440. // Vertices
  26441. var i;
  26442. var j;
  26443. for (i = 0; i <= radialSegments; i++) {
  26444. var modI = i % radialSegments;
  26445. var u = modI / radialSegments * 2 * p * Math.PI;
  26446. var p1 = getPos(u);
  26447. var p2 = getPos(u + 0.01);
  26448. var tang = p2.subtract(p1);
  26449. var n = p2.add(p1);
  26450. var bitan = BABYLON.Vector3.Cross(tang, n);
  26451. n = BABYLON.Vector3.Cross(bitan, tang);
  26452. bitan.normalize();
  26453. n.normalize();
  26454. for (j = 0; j < tubularSegments; j++) {
  26455. var modJ = j % tubularSegments;
  26456. var v = modJ / tubularSegments * 2 * Math.PI;
  26457. var cx = -tube * Math.cos(v);
  26458. var cy = tube * Math.sin(v);
  26459. positions.push(p1.x + cx * n.x + cy * bitan.x);
  26460. positions.push(p1.y + cx * n.y + cy * bitan.y);
  26461. positions.push(p1.z + cx * n.z + cy * bitan.z);
  26462. uvs.push(i / radialSegments);
  26463. uvs.push(j / tubularSegments);
  26464. }
  26465. }
  26466. for (i = 0; i < radialSegments; i++) {
  26467. for (j = 0; j < tubularSegments; j++) {
  26468. var jNext = (j + 1) % tubularSegments;
  26469. var a = i * tubularSegments + j;
  26470. var b = (i + 1) * tubularSegments + j;
  26471. var c = (i + 1) * tubularSegments + jNext;
  26472. var d = i * tubularSegments + jNext;
  26473. indices.push(d);
  26474. indices.push(b);
  26475. indices.push(a);
  26476. indices.push(d);
  26477. indices.push(c);
  26478. indices.push(b);
  26479. }
  26480. }
  26481. // Normals
  26482. VertexData.ComputeNormals(positions, indices, normals);
  26483. // Sides
  26484. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26485. // Result
  26486. var vertexData = new VertexData();
  26487. vertexData.indices = indices;
  26488. vertexData.positions = positions;
  26489. vertexData.normals = normals;
  26490. vertexData.uvs = uvs;
  26491. return vertexData;
  26492. };
  26493. // Tools
  26494. /**
  26495. * @param {any} - positions (number[] or Float32Array)
  26496. * @param {any} - indices (number[] or Uint16Array)
  26497. * @param {any} - normals (number[] or Float32Array)
  26498. * options (optional) :
  26499. * facetPositions : optional array of facet positions (vector3)
  26500. * facetNormals : optional array of facet normals (vector3)
  26501. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  26502. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  26503. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  26504. * bbSize : optional bounding box size data, required for facetPartitioning computation
  26505. * bInfo : optional bounding info, required for facetPartitioning computation
  26506. */
  26507. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  26508. // temporary scalar variables
  26509. var index = 0; // facet index
  26510. var p1p2x = 0.0; // p1p2 vector x coordinate
  26511. var p1p2y = 0.0; // p1p2 vector y coordinate
  26512. var p1p2z = 0.0; // p1p2 vector z coordinate
  26513. var p3p2x = 0.0; // p3p2 vector x coordinate
  26514. var p3p2y = 0.0; // p3p2 vector y coordinate
  26515. var p3p2z = 0.0; // p3p2 vector z coordinate
  26516. var faceNormalx = 0.0; // facet normal x coordinate
  26517. var faceNormaly = 0.0; // facet normal y coordinate
  26518. var faceNormalz = 0.0; // facet normal z coordinate
  26519. var length = 0.0; // facet normal length before normalization
  26520. var v1x = 0; // vector1 x index in the positions array
  26521. var v1y = 0; // vector1 y index in the positions array
  26522. var v1z = 0; // vector1 z index in the positions array
  26523. var v2x = 0; // vector2 x index in the positions array
  26524. var v2y = 0; // vector2 y index in the positions array
  26525. var v2z = 0; // vector2 z index in the positions array
  26526. var v3x = 0; // vector3 x index in the positions array
  26527. var v3y = 0; // vector3 y index in the positions array
  26528. var v3z = 0; // vector3 z index in the positions array
  26529. var computeFacetNormals = false;
  26530. var computeFacetPositions = false;
  26531. var computeFacetPartitioning = false;
  26532. var faceNormalSign = 1;
  26533. if (options) {
  26534. computeFacetNormals = (options.facetNormals) ? true : false;
  26535. computeFacetPositions = (options.facetPositions) ? true : false;
  26536. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  26537. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  26538. }
  26539. // facetPartitioning reinit if needed
  26540. if (computeFacetPartitioning) {
  26541. var ox = 0; // X partitioning index for facet position
  26542. var oy = 0; // Y partinioning index for facet position
  26543. var oz = 0; // Z partinioning index for facet position
  26544. var b1x = 0; // X partitioning index for facet v1 vertex
  26545. var b1y = 0; // Y partitioning index for facet v1 vertex
  26546. var b1z = 0; // z partitioning index for facet v1 vertex
  26547. var b2x = 0; // X partitioning index for facet v2 vertex
  26548. var b2y = 0; // Y partitioning index for facet v2 vertex
  26549. var b2z = 0; // Z partitioning index for facet v2 vertex
  26550. var b3x = 0; // X partitioning index for facet v3 vertex
  26551. var b3y = 0; // Y partitioning index for facet v3 vertex
  26552. var b3z = 0; // Z partitioning index for facet v3 vertex
  26553. var block_idx_o = 0; // facet barycenter block index
  26554. var block_idx_v1 = 0; // v1 vertex block index
  26555. var block_idx_v2 = 0; // v2 vertex block index
  26556. var block_idx_v3 = 0; // v3 vertex block index
  26557. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  26558. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  26559. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  26560. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  26561. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  26562. var subSq = options.subDiv.max * options.subDiv.max;
  26563. options.facetPartitioning.length = 0;
  26564. }
  26565. // reset the normals
  26566. for (index = 0; index < positions.length; index++) {
  26567. normals[index] = 0.0;
  26568. }
  26569. // Loop : 1 indice triplet = 1 facet
  26570. var nbFaces = indices.length / 3;
  26571. for (index = 0; index < nbFaces; index++) {
  26572. // get the indexes of the coordinates of each vertex of the facet
  26573. v1x = indices[index * 3] * 3;
  26574. v1y = v1x + 1;
  26575. v1z = v1x + 2;
  26576. v2x = indices[index * 3 + 1] * 3;
  26577. v2y = v2x + 1;
  26578. v2z = v2x + 2;
  26579. v3x = indices[index * 3 + 2] * 3;
  26580. v3y = v3x + 1;
  26581. v3z = v3x + 2;
  26582. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  26583. p1p2y = positions[v1y] - positions[v2y];
  26584. p1p2z = positions[v1z] - positions[v2z];
  26585. p3p2x = positions[v3x] - positions[v2x];
  26586. p3p2y = positions[v3y] - positions[v2y];
  26587. p3p2z = positions[v3z] - positions[v2z];
  26588. // compute the face normal with the cross product
  26589. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  26590. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  26591. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  26592. // normalize this normal and store it in the array facetData
  26593. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26594. length = (length === 0) ? 1.0 : length;
  26595. faceNormalx /= length;
  26596. faceNormaly /= length;
  26597. faceNormalz /= length;
  26598. if (computeFacetNormals) {
  26599. options.facetNormals[index].x = faceNormalx;
  26600. options.facetNormals[index].y = faceNormaly;
  26601. options.facetNormals[index].z = faceNormalz;
  26602. }
  26603. if (computeFacetPositions) {
  26604. // compute and the facet barycenter coordinates in the array facetPositions
  26605. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  26606. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  26607. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  26608. }
  26609. if (computeFacetPartitioning) {
  26610. // store the facet indexes in arrays in the main facetPartitioning array :
  26611. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  26612. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26613. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26614. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26615. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26616. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26617. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26618. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26619. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26620. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26621. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  26622. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  26623. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  26624. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  26625. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  26626. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  26627. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  26628. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  26629. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  26630. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  26631. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  26632. // push each facet index in each block containing the vertex
  26633. options.facetPartitioning[block_idx_v1].push(index);
  26634. if (block_idx_v2 != block_idx_v1) {
  26635. options.facetPartitioning[block_idx_v2].push(index);
  26636. }
  26637. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  26638. options.facetPartitioning[block_idx_v3].push(index);
  26639. }
  26640. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  26641. options.facetPartitioning[block_idx_o].push(index);
  26642. }
  26643. }
  26644. // compute the normals anyway
  26645. normals[v1x] += faceNormalx; // accumulate all the normals per face
  26646. normals[v1y] += faceNormaly;
  26647. normals[v1z] += faceNormalz;
  26648. normals[v2x] += faceNormalx;
  26649. normals[v2y] += faceNormaly;
  26650. normals[v2z] += faceNormalz;
  26651. normals[v3x] += faceNormalx;
  26652. normals[v3y] += faceNormaly;
  26653. normals[v3z] += faceNormalz;
  26654. }
  26655. // last normalization of each normal
  26656. for (index = 0; index < normals.length / 3; index++) {
  26657. faceNormalx = normals[index * 3];
  26658. faceNormaly = normals[index * 3 + 1];
  26659. faceNormalz = normals[index * 3 + 2];
  26660. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  26661. length = (length === 0) ? 1.0 : length;
  26662. faceNormalx /= length;
  26663. faceNormaly /= length;
  26664. faceNormalz /= length;
  26665. normals[index * 3] = faceNormalx;
  26666. normals[index * 3 + 1] = faceNormaly;
  26667. normals[index * 3 + 2] = faceNormalz;
  26668. }
  26669. };
  26670. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  26671. var li = indices.length;
  26672. var ln = normals.length;
  26673. var i;
  26674. var n;
  26675. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26676. switch (sideOrientation) {
  26677. case BABYLON.Mesh.FRONTSIDE:
  26678. // nothing changed
  26679. break;
  26680. case BABYLON.Mesh.BACKSIDE:
  26681. var tmp;
  26682. // indices
  26683. for (i = 0; i < li; i += 3) {
  26684. tmp = indices[i];
  26685. indices[i] = indices[i + 2];
  26686. indices[i + 2] = tmp;
  26687. }
  26688. // normals
  26689. for (n = 0; n < ln; n++) {
  26690. normals[n] = -normals[n];
  26691. }
  26692. break;
  26693. case BABYLON.Mesh.DOUBLESIDE:
  26694. // positions
  26695. var lp = positions.length;
  26696. var l = lp / 3;
  26697. for (var p = 0; p < lp; p++) {
  26698. positions[lp + p] = positions[p];
  26699. }
  26700. // indices
  26701. for (i = 0; i < li; i += 3) {
  26702. indices[i + li] = indices[i + 2] + l;
  26703. indices[i + 1 + li] = indices[i + 1] + l;
  26704. indices[i + 2 + li] = indices[i] + l;
  26705. }
  26706. // normals
  26707. for (n = 0; n < ln; n++) {
  26708. normals[ln + n] = -normals[n];
  26709. }
  26710. // uvs
  26711. var lu = uvs.length;
  26712. var u = 0;
  26713. for (u = 0; u < lu; u++) {
  26714. uvs[u + lu] = uvs[u];
  26715. }
  26716. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  26717. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  26718. u = 0;
  26719. for (i = 0; i < lu / 2; i++) {
  26720. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  26721. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  26722. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  26723. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  26724. u += 2;
  26725. }
  26726. break;
  26727. }
  26728. };
  26729. /**
  26730. * Creates a new VertexData from the imported parameters.
  26731. */
  26732. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  26733. var vertexData = new VertexData();
  26734. // positions
  26735. var positions = parsedVertexData.positions;
  26736. if (positions) {
  26737. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  26738. }
  26739. // normals
  26740. var normals = parsedVertexData.normals;
  26741. if (normals) {
  26742. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  26743. }
  26744. // tangents
  26745. var tangents = parsedVertexData.tangents;
  26746. if (tangents) {
  26747. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  26748. }
  26749. // uvs
  26750. var uvs = parsedVertexData.uvs;
  26751. if (uvs) {
  26752. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  26753. }
  26754. // uv2s
  26755. var uv2s = parsedVertexData.uv2s;
  26756. if (uv2s) {
  26757. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  26758. }
  26759. // uv3s
  26760. var uv3s = parsedVertexData.uv3s;
  26761. if (uv3s) {
  26762. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  26763. }
  26764. // uv4s
  26765. var uv4s = parsedVertexData.uv4s;
  26766. if (uv4s) {
  26767. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  26768. }
  26769. // uv5s
  26770. var uv5s = parsedVertexData.uv5s;
  26771. if (uv5s) {
  26772. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  26773. }
  26774. // uv6s
  26775. var uv6s = parsedVertexData.uv6s;
  26776. if (uv6s) {
  26777. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  26778. }
  26779. // colors
  26780. var colors = parsedVertexData.colors;
  26781. if (colors) {
  26782. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  26783. }
  26784. // matricesIndices
  26785. var matricesIndices = parsedVertexData.matricesIndices;
  26786. if (matricesIndices) {
  26787. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  26788. }
  26789. // matricesWeights
  26790. var matricesWeights = parsedVertexData.matricesWeights;
  26791. if (matricesWeights) {
  26792. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  26793. }
  26794. // indices
  26795. var indices = parsedVertexData.indices;
  26796. if (indices) {
  26797. vertexData.indices = indices;
  26798. }
  26799. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  26800. };
  26801. return VertexData;
  26802. }());
  26803. BABYLON.VertexData = VertexData;
  26804. })(BABYLON || (BABYLON = {}));
  26805. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  26806. var BABYLON;
  26807. (function (BABYLON) {
  26808. var Geometry = (function () {
  26809. function Geometry(id, scene, vertexData, updatable, mesh) {
  26810. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26811. this._totalVertices = 0;
  26812. this._isDisposed = false;
  26813. this.id = id;
  26814. this._engine = scene.getEngine();
  26815. this._meshes = [];
  26816. this._scene = scene;
  26817. //Init vertex buffer cache
  26818. this._vertexBuffers = {};
  26819. this._indices = [];
  26820. // vertexData
  26821. if (vertexData) {
  26822. this.setAllVerticesData(vertexData, updatable);
  26823. }
  26824. else {
  26825. this._totalVertices = 0;
  26826. this._indices = [];
  26827. }
  26828. if (this._engine.getCaps().vertexArrayObject) {
  26829. this._vertexArrayObjects = {};
  26830. }
  26831. // applyToMesh
  26832. if (mesh) {
  26833. if (mesh.getClassName() === "LinesMesh") {
  26834. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  26835. this.updateExtend();
  26836. }
  26837. this.applyToMesh(mesh);
  26838. mesh.computeWorldMatrix(true);
  26839. }
  26840. }
  26841. Object.defineProperty(Geometry.prototype, "boundingBias", {
  26842. /**
  26843. * 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
  26844. * @returns The Bias Vector
  26845. */
  26846. get: function () {
  26847. return this._boundingBias;
  26848. },
  26849. set: function (value) {
  26850. if (this._boundingBias && this._boundingBias.equals(value)) {
  26851. return;
  26852. }
  26853. this._boundingBias = value.clone();
  26854. this.updateBoundingInfo(true, null);
  26855. },
  26856. enumerable: true,
  26857. configurable: true
  26858. });
  26859. Object.defineProperty(Geometry.prototype, "extend", {
  26860. get: function () {
  26861. return this._extend;
  26862. },
  26863. enumerable: true,
  26864. configurable: true
  26865. });
  26866. Geometry.prototype.getScene = function () {
  26867. return this._scene;
  26868. };
  26869. Geometry.prototype.getEngine = function () {
  26870. return this._engine;
  26871. };
  26872. Geometry.prototype.isReady = function () {
  26873. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  26874. };
  26875. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  26876. get: function () {
  26877. for (var index = 0; index < this._meshes.length; index++) {
  26878. if (!this._meshes[index].doNotSerialize) {
  26879. return false;
  26880. }
  26881. }
  26882. return true;
  26883. },
  26884. enumerable: true,
  26885. configurable: true
  26886. });
  26887. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  26888. vertexData.applyToGeometry(this, updatable);
  26889. this.notifyUpdate();
  26890. };
  26891. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26892. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  26893. this.setVerticesBuffer(buffer);
  26894. };
  26895. Geometry.prototype.removeVerticesData = function (kind) {
  26896. if (this._vertexBuffers[kind]) {
  26897. this._vertexBuffers[kind].dispose();
  26898. delete this._vertexBuffers[kind];
  26899. }
  26900. };
  26901. Geometry.prototype.setVerticesBuffer = function (buffer) {
  26902. var kind = buffer.getKind();
  26903. if (this._vertexBuffers[kind]) {
  26904. this._vertexBuffers[kind].dispose();
  26905. }
  26906. this._vertexBuffers[kind] = buffer;
  26907. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26908. var data = buffer.getData();
  26909. var stride = buffer.getStrideSize();
  26910. this._totalVertices = data.length / stride;
  26911. this.updateExtend(data, stride);
  26912. this._resetPointsArrayCache();
  26913. var meshes = this._meshes;
  26914. var numOfMeshes = meshes.length;
  26915. for (var index = 0; index < numOfMeshes; index++) {
  26916. var mesh = meshes[index];
  26917. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26918. mesh._createGlobalSubMesh();
  26919. mesh.computeWorldMatrix(true);
  26920. }
  26921. }
  26922. this.notifyUpdate(kind);
  26923. if (this._vertexArrayObjects) {
  26924. this._disposeVertexArrayObjects();
  26925. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  26926. }
  26927. };
  26928. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  26929. var vertexBuffer = this.getVertexBuffer(kind);
  26930. if (!vertexBuffer) {
  26931. return;
  26932. }
  26933. vertexBuffer.updateDirectly(data, offset);
  26934. this.notifyUpdate(kind);
  26935. };
  26936. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  26937. var vertexBuffer = this.getVertexBuffer(kind);
  26938. if (!vertexBuffer) {
  26939. return;
  26940. }
  26941. vertexBuffer.update(data);
  26942. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26943. var stride = vertexBuffer.getStrideSize();
  26944. this._totalVertices = data.length / stride;
  26945. this.updateBoundingInfo(updateExtends, data);
  26946. }
  26947. this.notifyUpdate(kind);
  26948. };
  26949. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  26950. if (updateExtends) {
  26951. this.updateExtend(data);
  26952. }
  26953. var meshes = this._meshes;
  26954. var numOfMeshes = meshes.length;
  26955. this._resetPointsArrayCache();
  26956. for (var index = 0; index < numOfMeshes; index++) {
  26957. var mesh = meshes[index];
  26958. if (updateExtends) {
  26959. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26960. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  26961. var subMesh = mesh.subMeshes[subIndex];
  26962. subMesh.refreshBoundingInfo();
  26963. }
  26964. }
  26965. }
  26966. };
  26967. Geometry.prototype._bind = function (effect, indexToBind) {
  26968. if (indexToBind === void 0) { indexToBind = undefined; }
  26969. if (indexToBind === undefined) {
  26970. indexToBind = this._indexBuffer;
  26971. }
  26972. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  26973. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  26974. return;
  26975. }
  26976. // Using VAO
  26977. if (!this._vertexArrayObjects[effect.key]) {
  26978. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  26979. }
  26980. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  26981. };
  26982. Geometry.prototype.getTotalVertices = function () {
  26983. if (!this.isReady()) {
  26984. return 0;
  26985. }
  26986. return this._totalVertices;
  26987. };
  26988. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  26989. var vertexBuffer = this.getVertexBuffer(kind);
  26990. if (!vertexBuffer) {
  26991. return null;
  26992. }
  26993. var orig = vertexBuffer.getData();
  26994. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  26995. return orig;
  26996. }
  26997. else {
  26998. var len = orig.length;
  26999. var copy = [];
  27000. for (var i = 0; i < len; i++) {
  27001. copy.push(orig[i]);
  27002. }
  27003. return copy;
  27004. }
  27005. };
  27006. Geometry.prototype.getVertexBuffer = function (kind) {
  27007. if (!this.isReady()) {
  27008. return null;
  27009. }
  27010. return this._vertexBuffers[kind];
  27011. };
  27012. Geometry.prototype.getVertexBuffers = function () {
  27013. if (!this.isReady()) {
  27014. return null;
  27015. }
  27016. return this._vertexBuffers;
  27017. };
  27018. Geometry.prototype.isVerticesDataPresent = function (kind) {
  27019. if (!this._vertexBuffers) {
  27020. if (this._delayInfo) {
  27021. return this._delayInfo.indexOf(kind) !== -1;
  27022. }
  27023. return false;
  27024. }
  27025. return this._vertexBuffers[kind] !== undefined;
  27026. };
  27027. Geometry.prototype.getVerticesDataKinds = function () {
  27028. var result = [];
  27029. var kind;
  27030. if (!this._vertexBuffers && this._delayInfo) {
  27031. for (kind in this._delayInfo) {
  27032. result.push(kind);
  27033. }
  27034. }
  27035. else {
  27036. for (kind in this._vertexBuffers) {
  27037. result.push(kind);
  27038. }
  27039. }
  27040. return result;
  27041. };
  27042. Geometry.prototype.setIndices = function (indices, totalVertices) {
  27043. if (this._indexBuffer) {
  27044. this._engine._releaseBuffer(this._indexBuffer);
  27045. }
  27046. this._disposeVertexArrayObjects();
  27047. this._indices = indices;
  27048. if (this._meshes.length !== 0 && this._indices) {
  27049. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27050. }
  27051. if (totalVertices !== undefined) {
  27052. this._totalVertices = totalVertices;
  27053. }
  27054. var meshes = this._meshes;
  27055. var numOfMeshes = meshes.length;
  27056. for (var index = 0; index < numOfMeshes; index++) {
  27057. meshes[index]._createGlobalSubMesh();
  27058. }
  27059. this.notifyUpdate();
  27060. };
  27061. Geometry.prototype.getTotalIndices = function () {
  27062. if (!this.isReady()) {
  27063. return 0;
  27064. }
  27065. return this._indices.length;
  27066. };
  27067. Geometry.prototype.getIndices = function (copyWhenShared) {
  27068. if (!this.isReady()) {
  27069. return null;
  27070. }
  27071. var orig = this._indices;
  27072. if (!copyWhenShared || this._meshes.length === 1) {
  27073. return orig;
  27074. }
  27075. else {
  27076. var len = orig.length;
  27077. var copy = [];
  27078. for (var i = 0; i < len; i++) {
  27079. copy.push(orig[i]);
  27080. }
  27081. return copy;
  27082. }
  27083. };
  27084. Geometry.prototype.getIndexBuffer = function () {
  27085. if (!this.isReady()) {
  27086. return null;
  27087. }
  27088. return this._indexBuffer;
  27089. };
  27090. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  27091. if (!effect || !this._vertexArrayObjects) {
  27092. return;
  27093. }
  27094. if (this._vertexArrayObjects[effect.key]) {
  27095. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  27096. delete this._vertexArrayObjects[effect.key];
  27097. }
  27098. };
  27099. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  27100. var meshes = this._meshes;
  27101. var index = meshes.indexOf(mesh);
  27102. if (index === -1) {
  27103. return;
  27104. }
  27105. meshes.splice(index, 1);
  27106. mesh._geometry = null;
  27107. if (meshes.length === 0 && shouldDispose) {
  27108. this.dispose();
  27109. }
  27110. };
  27111. Geometry.prototype.applyToMesh = function (mesh) {
  27112. if (mesh._geometry === this) {
  27113. return;
  27114. }
  27115. var previousGeometry = mesh._geometry;
  27116. if (previousGeometry) {
  27117. previousGeometry.releaseForMesh(mesh);
  27118. }
  27119. var meshes = this._meshes;
  27120. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  27121. mesh._geometry = this;
  27122. this._scene.pushGeometry(this);
  27123. meshes.push(mesh);
  27124. if (this.isReady()) {
  27125. this._applyToMesh(mesh);
  27126. }
  27127. else {
  27128. mesh._boundingInfo = this._boundingInfo;
  27129. }
  27130. };
  27131. Geometry.prototype.updateExtend = function (data, stride) {
  27132. if (data === void 0) { data = null; }
  27133. if (!data) {
  27134. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  27135. }
  27136. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  27137. };
  27138. Geometry.prototype._applyToMesh = function (mesh) {
  27139. var numOfMeshes = this._meshes.length;
  27140. // vertexBuffers
  27141. for (var kind in this._vertexBuffers) {
  27142. if (numOfMeshes === 1) {
  27143. this._vertexBuffers[kind].create();
  27144. }
  27145. var buffer = this._vertexBuffers[kind].getBuffer();
  27146. if (buffer)
  27147. buffer.references = numOfMeshes;
  27148. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27149. if (!this._extend) {
  27150. this.updateExtend(this._vertexBuffers[kind].getData());
  27151. }
  27152. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27153. mesh._createGlobalSubMesh();
  27154. //bounding info was just created again, world matrix should be applied again.
  27155. mesh._updateBoundingInfo();
  27156. }
  27157. }
  27158. // indexBuffer
  27159. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  27160. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27161. }
  27162. if (this._indexBuffer) {
  27163. this._indexBuffer.references = numOfMeshes;
  27164. }
  27165. };
  27166. Geometry.prototype.notifyUpdate = function (kind) {
  27167. if (this.onGeometryUpdated) {
  27168. this.onGeometryUpdated(this, kind);
  27169. }
  27170. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  27171. var mesh = _a[_i];
  27172. mesh._markSubMeshesAsAttributesDirty();
  27173. }
  27174. };
  27175. Geometry.prototype.load = function (scene, onLoaded) {
  27176. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27177. return;
  27178. }
  27179. if (this.isReady()) {
  27180. if (onLoaded) {
  27181. onLoaded();
  27182. }
  27183. return;
  27184. }
  27185. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27186. this._queueLoad(scene, onLoaded);
  27187. };
  27188. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  27189. var _this = this;
  27190. scene._addPendingData(this);
  27191. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27192. _this._delayLoadingFunction(JSON.parse(data), _this);
  27193. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27194. _this._delayInfo = [];
  27195. scene._removePendingData(_this);
  27196. var meshes = _this._meshes;
  27197. var numOfMeshes = meshes.length;
  27198. for (var index = 0; index < numOfMeshes; index++) {
  27199. _this._applyToMesh(meshes[index]);
  27200. }
  27201. if (onLoaded) {
  27202. onLoaded();
  27203. }
  27204. }, function () { }, scene.database);
  27205. };
  27206. /**
  27207. * Invert the geometry to move from a right handed system to a left handed one.
  27208. */
  27209. Geometry.prototype.toLeftHanded = function () {
  27210. // Flip faces
  27211. var tIndices = this.getIndices(false);
  27212. if (tIndices != null && tIndices.length > 0) {
  27213. for (var i = 0; i < tIndices.length; i += 3) {
  27214. var tTemp = tIndices[i + 0];
  27215. tIndices[i + 0] = tIndices[i + 2];
  27216. tIndices[i + 2] = tTemp;
  27217. }
  27218. this.setIndices(tIndices);
  27219. }
  27220. // Negate position.z
  27221. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  27222. if (tPositions != null && tPositions.length > 0) {
  27223. for (var i = 0; i < tPositions.length; i += 3) {
  27224. tPositions[i + 2] = -tPositions[i + 2];
  27225. }
  27226. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  27227. }
  27228. // Negate normal.z
  27229. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  27230. if (tNormals != null && tNormals.length > 0) {
  27231. for (var i = 0; i < tNormals.length; i += 3) {
  27232. tNormals[i + 2] = -tNormals[i + 2];
  27233. }
  27234. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  27235. }
  27236. };
  27237. // Cache
  27238. Geometry.prototype._resetPointsArrayCache = function () {
  27239. this._positions = null;
  27240. };
  27241. Geometry.prototype._generatePointsArray = function () {
  27242. if (this._positions)
  27243. return true;
  27244. this._positions = [];
  27245. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27246. if (!data) {
  27247. return false;
  27248. }
  27249. for (var index = 0; index < data.length; index += 3) {
  27250. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  27251. }
  27252. return true;
  27253. };
  27254. Geometry.prototype.isDisposed = function () {
  27255. return this._isDisposed;
  27256. };
  27257. Geometry.prototype._disposeVertexArrayObjects = function () {
  27258. if (this._vertexArrayObjects) {
  27259. for (var kind in this._vertexArrayObjects) {
  27260. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  27261. }
  27262. this._vertexArrayObjects = {};
  27263. }
  27264. };
  27265. Geometry.prototype.dispose = function () {
  27266. var meshes = this._meshes;
  27267. var numOfMeshes = meshes.length;
  27268. var index;
  27269. for (index = 0; index < numOfMeshes; index++) {
  27270. this.releaseForMesh(meshes[index]);
  27271. }
  27272. this._meshes = [];
  27273. this._disposeVertexArrayObjects();
  27274. for (var kind in this._vertexBuffers) {
  27275. this._vertexBuffers[kind].dispose();
  27276. }
  27277. this._vertexBuffers = {};
  27278. this._totalVertices = 0;
  27279. if (this._indexBuffer) {
  27280. this._engine._releaseBuffer(this._indexBuffer);
  27281. }
  27282. this._indexBuffer = null;
  27283. this._indices = [];
  27284. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27285. this.delayLoadingFile = null;
  27286. this._delayLoadingFunction = null;
  27287. this._delayInfo = [];
  27288. this._boundingInfo = null;
  27289. this._scene.removeGeometry(this);
  27290. this._isDisposed = true;
  27291. };
  27292. Geometry.prototype.copy = function (id) {
  27293. var vertexData = new BABYLON.VertexData();
  27294. vertexData.indices = [];
  27295. var indices = this.getIndices();
  27296. for (var index = 0; index < indices.length; index++) {
  27297. vertexData.indices.push(indices[index]);
  27298. }
  27299. var updatable = false;
  27300. var stopChecking = false;
  27301. var kind;
  27302. for (kind in this._vertexBuffers) {
  27303. // using slice() to make a copy of the array and not just reference it
  27304. var data = this.getVerticesData(kind);
  27305. if (data instanceof Float32Array) {
  27306. vertexData.set(new Float32Array(data), kind);
  27307. }
  27308. else {
  27309. vertexData.set(data.slice(0), kind);
  27310. }
  27311. if (!stopChecking) {
  27312. updatable = this.getVertexBuffer(kind).isUpdatable();
  27313. stopChecking = !updatable;
  27314. }
  27315. }
  27316. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  27317. geometry.delayLoadState = this.delayLoadState;
  27318. geometry.delayLoadingFile = this.delayLoadingFile;
  27319. geometry._delayLoadingFunction = this._delayLoadingFunction;
  27320. for (kind in this._delayInfo) {
  27321. geometry._delayInfo = geometry._delayInfo || [];
  27322. geometry._delayInfo.push(kind);
  27323. }
  27324. // Bounding info
  27325. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  27326. return geometry;
  27327. };
  27328. Geometry.prototype.serialize = function () {
  27329. var serializationObject = {};
  27330. serializationObject.id = this.id;
  27331. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  27332. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27333. }
  27334. return serializationObject;
  27335. };
  27336. Geometry.prototype.toNumberArray = function (origin) {
  27337. if (Array.isArray(origin)) {
  27338. return origin;
  27339. }
  27340. else {
  27341. return Array.prototype.slice.call(origin);
  27342. }
  27343. };
  27344. Geometry.prototype.serializeVerticeData = function () {
  27345. var serializationObject = this.serialize();
  27346. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27347. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  27348. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  27349. serializationObject.positions._updatable = true;
  27350. }
  27351. }
  27352. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27353. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  27354. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  27355. serializationObject.normals._updatable = true;
  27356. }
  27357. }
  27358. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27359. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  27360. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  27361. serializationObject.uvs._updatable = true;
  27362. }
  27363. }
  27364. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27365. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  27366. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  27367. serializationObject.uv2s._updatable = true;
  27368. }
  27369. }
  27370. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27371. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  27372. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  27373. serializationObject.uv3s._updatable = true;
  27374. }
  27375. }
  27376. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27377. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  27378. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  27379. serializationObject.uv4s._updatable = true;
  27380. }
  27381. }
  27382. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27383. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  27384. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  27385. serializationObject.uv5s._updatable = true;
  27386. }
  27387. }
  27388. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27389. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  27390. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  27391. serializationObject.uv6s._updatable = true;
  27392. }
  27393. }
  27394. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27395. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  27396. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  27397. serializationObject.colors._updatable = true;
  27398. }
  27399. }
  27400. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27401. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  27402. serializationObject.matricesIndices._isExpanded = true;
  27403. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  27404. serializationObject.matricesIndices._updatable = true;
  27405. }
  27406. }
  27407. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27408. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  27409. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  27410. serializationObject.matricesWeights._updatable = true;
  27411. }
  27412. }
  27413. serializationObject.indices = this.toNumberArray(this.getIndices());
  27414. return serializationObject;
  27415. };
  27416. // Statics
  27417. Geometry.ExtractFromMesh = function (mesh, id) {
  27418. var geometry = mesh._geometry;
  27419. if (!geometry) {
  27420. return null;
  27421. }
  27422. return geometry.copy(id);
  27423. };
  27424. /**
  27425. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  27426. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  27427. * Be aware Math.random() could cause collisions, but:
  27428. * "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"
  27429. */
  27430. Geometry.RandomId = function () {
  27431. return BABYLON.Tools.RandomId();
  27432. };
  27433. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  27434. var scene = mesh.getScene();
  27435. // Geometry
  27436. var geometryId = parsedGeometry.geometryId;
  27437. if (geometryId) {
  27438. var geometry = scene.getGeometryByID(geometryId);
  27439. if (geometry) {
  27440. geometry.applyToMesh(mesh);
  27441. }
  27442. }
  27443. else if (parsedGeometry instanceof ArrayBuffer) {
  27444. var binaryInfo = mesh._binaryInfo;
  27445. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  27446. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  27447. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  27448. }
  27449. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  27450. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  27451. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  27452. }
  27453. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  27454. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  27455. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  27456. }
  27457. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  27458. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  27459. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  27460. }
  27461. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  27462. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  27463. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  27464. }
  27465. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  27466. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  27467. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  27468. }
  27469. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  27470. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  27471. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  27472. }
  27473. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  27474. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  27475. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  27476. }
  27477. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  27478. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  27479. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  27480. }
  27481. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  27482. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  27483. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  27484. }
  27485. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  27486. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  27487. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  27488. }
  27489. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  27490. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  27491. mesh.setIndices(indicesData);
  27492. }
  27493. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  27494. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  27495. mesh.subMeshes = [];
  27496. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  27497. var materialIndex = subMeshesData[(i * 5) + 0];
  27498. var verticesStart = subMeshesData[(i * 5) + 1];
  27499. var verticesCount = subMeshesData[(i * 5) + 2];
  27500. var indexStart = subMeshesData[(i * 5) + 3];
  27501. var indexCount = subMeshesData[(i * 5) + 4];
  27502. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  27503. }
  27504. }
  27505. }
  27506. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  27507. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  27508. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  27509. if (parsedGeometry.uvs) {
  27510. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  27511. }
  27512. if (parsedGeometry.uvs2) {
  27513. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  27514. }
  27515. if (parsedGeometry.uvs3) {
  27516. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  27517. }
  27518. if (parsedGeometry.uvs4) {
  27519. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  27520. }
  27521. if (parsedGeometry.uvs5) {
  27522. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  27523. }
  27524. if (parsedGeometry.uvs6) {
  27525. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  27526. }
  27527. if (parsedGeometry.colors) {
  27528. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  27529. }
  27530. if (parsedGeometry.matricesIndices) {
  27531. if (!parsedGeometry.matricesIndices._isExpanded) {
  27532. var floatIndices = [];
  27533. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  27534. var matricesIndex = parsedGeometry.matricesIndices[i];
  27535. floatIndices.push(matricesIndex & 0x000000FF);
  27536. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27537. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27538. floatIndices.push(matricesIndex >> 24);
  27539. }
  27540. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  27541. }
  27542. else {
  27543. delete parsedGeometry.matricesIndices._isExpanded;
  27544. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  27545. }
  27546. }
  27547. if (parsedGeometry.matricesIndicesExtra) {
  27548. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  27549. var floatIndices = [];
  27550. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  27551. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  27552. floatIndices.push(matricesIndex & 0x000000FF);
  27553. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  27554. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  27555. floatIndices.push(matricesIndex >> 24);
  27556. }
  27557. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  27558. }
  27559. else {
  27560. delete parsedGeometry.matricesIndices._isExpanded;
  27561. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  27562. }
  27563. }
  27564. if (parsedGeometry.matricesWeights) {
  27565. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  27566. }
  27567. if (parsedGeometry.matricesWeightsExtra) {
  27568. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  27569. }
  27570. mesh.setIndices(parsedGeometry.indices);
  27571. }
  27572. // SubMeshes
  27573. if (parsedGeometry.subMeshes) {
  27574. mesh.subMeshes = [];
  27575. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  27576. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  27577. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  27578. }
  27579. }
  27580. // Flat shading
  27581. if (mesh._shouldGenerateFlatShading) {
  27582. mesh.convertToFlatShadedMesh();
  27583. delete mesh._shouldGenerateFlatShading;
  27584. }
  27585. // Update
  27586. mesh.computeWorldMatrix(true);
  27587. // Octree
  27588. if (scene['_selectionOctree']) {
  27589. scene['_selectionOctree'].addMesh(mesh);
  27590. }
  27591. };
  27592. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  27593. if (scene.getGeometryByID(parsedVertexData.id)) {
  27594. return null; // null since geometry could be something else than a box...
  27595. }
  27596. var geometry = new Geometry(parsedVertexData.id, scene);
  27597. if (BABYLON.Tags) {
  27598. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  27599. }
  27600. if (parsedVertexData.delayLoadingFile) {
  27601. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27602. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  27603. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  27604. geometry._delayInfo = [];
  27605. if (parsedVertexData.hasUVs) {
  27606. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27607. }
  27608. if (parsedVertexData.hasUVs2) {
  27609. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27610. }
  27611. if (parsedVertexData.hasUVs3) {
  27612. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27613. }
  27614. if (parsedVertexData.hasUVs4) {
  27615. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27616. }
  27617. if (parsedVertexData.hasUVs5) {
  27618. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  27619. }
  27620. if (parsedVertexData.hasUVs6) {
  27621. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  27622. }
  27623. if (parsedVertexData.hasColors) {
  27624. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27625. }
  27626. if (parsedVertexData.hasMatricesIndices) {
  27627. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27628. }
  27629. if (parsedVertexData.hasMatricesWeights) {
  27630. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27631. }
  27632. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  27633. }
  27634. else {
  27635. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  27636. }
  27637. scene.pushGeometry(geometry, true);
  27638. return geometry;
  27639. };
  27640. return Geometry;
  27641. }());
  27642. BABYLON.Geometry = Geometry;
  27643. /////// Primitives //////////////////////////////////////////////
  27644. (function (Geometry) {
  27645. var Primitives;
  27646. (function (Primitives) {
  27647. /// Abstract class
  27648. var _Primitive = (function (_super) {
  27649. __extends(_Primitive, _super);
  27650. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  27651. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  27652. _this._canBeRegenerated = _canBeRegenerated;
  27653. _this._beingRegenerated = true;
  27654. _this.regenerate();
  27655. _this._beingRegenerated = false;
  27656. return _this;
  27657. }
  27658. _Primitive.prototype.canBeRegenerated = function () {
  27659. return this._canBeRegenerated;
  27660. };
  27661. _Primitive.prototype.regenerate = function () {
  27662. if (!this._canBeRegenerated) {
  27663. return;
  27664. }
  27665. this._beingRegenerated = true;
  27666. this.setAllVerticesData(this._regenerateVertexData(), false);
  27667. this._beingRegenerated = false;
  27668. };
  27669. _Primitive.prototype.asNewGeometry = function (id) {
  27670. return _super.prototype.copy.call(this, id);
  27671. };
  27672. // overrides
  27673. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  27674. if (!this._beingRegenerated) {
  27675. return;
  27676. }
  27677. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  27678. };
  27679. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  27680. if (!this._beingRegenerated) {
  27681. return;
  27682. }
  27683. _super.prototype.setVerticesData.call(this, kind, data, false);
  27684. };
  27685. // to override
  27686. // protected
  27687. _Primitive.prototype._regenerateVertexData = function () {
  27688. throw new Error("Abstract method");
  27689. };
  27690. _Primitive.prototype.copy = function (id) {
  27691. throw new Error("Must be overriden in sub-classes.");
  27692. };
  27693. _Primitive.prototype.serialize = function () {
  27694. var serializationObject = _super.prototype.serialize.call(this);
  27695. serializationObject.canBeRegenerated = this.canBeRegenerated();
  27696. return serializationObject;
  27697. };
  27698. return _Primitive;
  27699. }(Geometry));
  27700. Primitives._Primitive = _Primitive;
  27701. var Ribbon = (function (_super) {
  27702. __extends(Ribbon, _super);
  27703. // Members
  27704. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  27705. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27706. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27707. _this.pathArray = pathArray;
  27708. _this.closeArray = closeArray;
  27709. _this.closePath = closePath;
  27710. _this.offset = offset;
  27711. _this.side = side;
  27712. return _this;
  27713. }
  27714. Ribbon.prototype._regenerateVertexData = function () {
  27715. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  27716. };
  27717. Ribbon.prototype.copy = function (id) {
  27718. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  27719. };
  27720. return Ribbon;
  27721. }(_Primitive));
  27722. Primitives.Ribbon = Ribbon;
  27723. var Box = (function (_super) {
  27724. __extends(Box, _super);
  27725. // Members
  27726. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  27727. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27728. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27729. _this.size = size;
  27730. _this.side = side;
  27731. return _this;
  27732. }
  27733. Box.prototype._regenerateVertexData = function () {
  27734. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  27735. };
  27736. Box.prototype.copy = function (id) {
  27737. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27738. };
  27739. Box.prototype.serialize = function () {
  27740. var serializationObject = _super.prototype.serialize.call(this);
  27741. serializationObject.size = this.size;
  27742. return serializationObject;
  27743. };
  27744. Box.Parse = function (parsedBox, scene) {
  27745. if (scene.getGeometryByID(parsedBox.id)) {
  27746. return null; // null since geometry could be something else than a box...
  27747. }
  27748. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  27749. if (BABYLON.Tags) {
  27750. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  27751. }
  27752. scene.pushGeometry(box, true);
  27753. return box;
  27754. };
  27755. return Box;
  27756. }(_Primitive));
  27757. Primitives.Box = Box;
  27758. var Sphere = (function (_super) {
  27759. __extends(Sphere, _super);
  27760. function Sphere(id, scene, segments, diameter, 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.segments = segments;
  27764. _this.diameter = diameter;
  27765. _this.side = side;
  27766. return _this;
  27767. }
  27768. Sphere.prototype._regenerateVertexData = function () {
  27769. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  27770. };
  27771. Sphere.prototype.copy = function (id) {
  27772. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  27773. };
  27774. Sphere.prototype.serialize = function () {
  27775. var serializationObject = _super.prototype.serialize.call(this);
  27776. serializationObject.segments = this.segments;
  27777. serializationObject.diameter = this.diameter;
  27778. return serializationObject;
  27779. };
  27780. Sphere.Parse = function (parsedSphere, scene) {
  27781. if (scene.getGeometryByID(parsedSphere.id)) {
  27782. return null; // null since geometry could be something else than a sphere...
  27783. }
  27784. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  27785. if (BABYLON.Tags) {
  27786. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  27787. }
  27788. scene.pushGeometry(sphere, true);
  27789. return sphere;
  27790. };
  27791. return Sphere;
  27792. }(_Primitive));
  27793. Primitives.Sphere = Sphere;
  27794. var Disc = (function (_super) {
  27795. __extends(Disc, _super);
  27796. // Members
  27797. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  27798. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27799. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27800. _this.radius = radius;
  27801. _this.tessellation = tessellation;
  27802. _this.side = side;
  27803. return _this;
  27804. }
  27805. Disc.prototype._regenerateVertexData = function () {
  27806. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  27807. };
  27808. Disc.prototype.copy = function (id) {
  27809. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  27810. };
  27811. return Disc;
  27812. }(_Primitive));
  27813. Primitives.Disc = Disc;
  27814. var Cylinder = (function (_super) {
  27815. __extends(Cylinder, _super);
  27816. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  27817. if (subdivisions === void 0) { subdivisions = 1; }
  27818. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27819. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27820. _this.height = height;
  27821. _this.diameterTop = diameterTop;
  27822. _this.diameterBottom = diameterBottom;
  27823. _this.tessellation = tessellation;
  27824. _this.subdivisions = subdivisions;
  27825. _this.side = side;
  27826. return _this;
  27827. }
  27828. Cylinder.prototype._regenerateVertexData = function () {
  27829. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  27830. };
  27831. Cylinder.prototype.copy = function (id) {
  27832. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  27833. };
  27834. Cylinder.prototype.serialize = function () {
  27835. var serializationObject = _super.prototype.serialize.call(this);
  27836. serializationObject.height = this.height;
  27837. serializationObject.diameterTop = this.diameterTop;
  27838. serializationObject.diameterBottom = this.diameterBottom;
  27839. serializationObject.tessellation = this.tessellation;
  27840. return serializationObject;
  27841. };
  27842. Cylinder.Parse = function (parsedCylinder, scene) {
  27843. if (scene.getGeometryByID(parsedCylinder.id)) {
  27844. return null; // null since geometry could be something else than a cylinder...
  27845. }
  27846. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  27847. if (BABYLON.Tags) {
  27848. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  27849. }
  27850. scene.pushGeometry(cylinder, true);
  27851. return cylinder;
  27852. };
  27853. return Cylinder;
  27854. }(_Primitive));
  27855. Primitives.Cylinder = Cylinder;
  27856. var Torus = (function (_super) {
  27857. __extends(Torus, _super);
  27858. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  27859. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27860. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27861. _this.diameter = diameter;
  27862. _this.thickness = thickness;
  27863. _this.tessellation = tessellation;
  27864. _this.side = side;
  27865. return _this;
  27866. }
  27867. Torus.prototype._regenerateVertexData = function () {
  27868. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  27869. };
  27870. Torus.prototype.copy = function (id) {
  27871. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  27872. };
  27873. Torus.prototype.serialize = function () {
  27874. var serializationObject = _super.prototype.serialize.call(this);
  27875. serializationObject.diameter = this.diameter;
  27876. serializationObject.thickness = this.thickness;
  27877. serializationObject.tessellation = this.tessellation;
  27878. return serializationObject;
  27879. };
  27880. Torus.Parse = function (parsedTorus, scene) {
  27881. if (scene.getGeometryByID(parsedTorus.id)) {
  27882. return null; // null since geometry could be something else than a torus...
  27883. }
  27884. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  27885. if (BABYLON.Tags) {
  27886. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  27887. }
  27888. scene.pushGeometry(torus, true);
  27889. return torus;
  27890. };
  27891. return Torus;
  27892. }(_Primitive));
  27893. Primitives.Torus = Torus;
  27894. var Ground = (function (_super) {
  27895. __extends(Ground, _super);
  27896. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  27897. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27898. _this.width = width;
  27899. _this.height = height;
  27900. _this.subdivisions = subdivisions;
  27901. return _this;
  27902. }
  27903. Ground.prototype._regenerateVertexData = function () {
  27904. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  27905. };
  27906. Ground.prototype.copy = function (id) {
  27907. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  27908. };
  27909. Ground.prototype.serialize = function () {
  27910. var serializationObject = _super.prototype.serialize.call(this);
  27911. serializationObject.width = this.width;
  27912. serializationObject.height = this.height;
  27913. serializationObject.subdivisions = this.subdivisions;
  27914. return serializationObject;
  27915. };
  27916. Ground.Parse = function (parsedGround, scene) {
  27917. if (scene.getGeometryByID(parsedGround.id)) {
  27918. return null; // null since geometry could be something else than a ground...
  27919. }
  27920. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  27921. if (BABYLON.Tags) {
  27922. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  27923. }
  27924. scene.pushGeometry(ground, true);
  27925. return ground;
  27926. };
  27927. return Ground;
  27928. }(_Primitive));
  27929. Primitives.Ground = Ground;
  27930. var TiledGround = (function (_super) {
  27931. __extends(TiledGround, _super);
  27932. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  27933. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27934. _this.xmin = xmin;
  27935. _this.zmin = zmin;
  27936. _this.xmax = xmax;
  27937. _this.zmax = zmax;
  27938. _this.subdivisions = subdivisions;
  27939. _this.precision = precision;
  27940. return _this;
  27941. }
  27942. TiledGround.prototype._regenerateVertexData = function () {
  27943. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  27944. };
  27945. TiledGround.prototype.copy = function (id) {
  27946. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  27947. };
  27948. return TiledGround;
  27949. }(_Primitive));
  27950. Primitives.TiledGround = TiledGround;
  27951. var Plane = (function (_super) {
  27952. __extends(Plane, _super);
  27953. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  27954. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27955. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27956. _this.size = size;
  27957. _this.side = side;
  27958. return _this;
  27959. }
  27960. Plane.prototype._regenerateVertexData = function () {
  27961. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  27962. };
  27963. Plane.prototype.copy = function (id) {
  27964. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27965. };
  27966. Plane.prototype.serialize = function () {
  27967. var serializationObject = _super.prototype.serialize.call(this);
  27968. serializationObject.size = this.size;
  27969. return serializationObject;
  27970. };
  27971. Plane.Parse = function (parsedPlane, scene) {
  27972. if (scene.getGeometryByID(parsedPlane.id)) {
  27973. return null; // null since geometry could be something else than a ground...
  27974. }
  27975. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  27976. if (BABYLON.Tags) {
  27977. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  27978. }
  27979. scene.pushGeometry(plane, true);
  27980. return plane;
  27981. };
  27982. return Plane;
  27983. }(_Primitive));
  27984. Primitives.Plane = Plane;
  27985. var TorusKnot = (function (_super) {
  27986. __extends(TorusKnot, _super);
  27987. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, 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.radius = radius;
  27991. _this.tube = tube;
  27992. _this.radialSegments = radialSegments;
  27993. _this.tubularSegments = tubularSegments;
  27994. _this.p = p;
  27995. _this.q = q;
  27996. _this.side = side;
  27997. return _this;
  27998. }
  27999. TorusKnot.prototype._regenerateVertexData = function () {
  28000. 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 });
  28001. };
  28002. TorusKnot.prototype.copy = function (id) {
  28003. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  28004. };
  28005. TorusKnot.prototype.serialize = function () {
  28006. var serializationObject = _super.prototype.serialize.call(this);
  28007. serializationObject.radius = this.radius;
  28008. serializationObject.tube = this.tube;
  28009. serializationObject.radialSegments = this.radialSegments;
  28010. serializationObject.tubularSegments = this.tubularSegments;
  28011. serializationObject.p = this.p;
  28012. serializationObject.q = this.q;
  28013. return serializationObject;
  28014. };
  28015. ;
  28016. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  28017. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  28018. return null; // null since geometry could be something else than a ground...
  28019. }
  28020. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  28021. if (BABYLON.Tags) {
  28022. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  28023. }
  28024. scene.pushGeometry(torusKnot, true);
  28025. return torusKnot;
  28026. };
  28027. return TorusKnot;
  28028. }(_Primitive));
  28029. Primitives.TorusKnot = TorusKnot;
  28030. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  28031. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  28032. })(BABYLON || (BABYLON = {}));
  28033. //# sourceMappingURL=babylon.geometry.js.map
  28034. var BABYLON;
  28035. (function (BABYLON) {
  28036. var PostProcessManager = (function () {
  28037. function PostProcessManager(scene) {
  28038. this._vertexBuffers = {};
  28039. this._scene = scene;
  28040. }
  28041. PostProcessManager.prototype._prepareBuffers = function () {
  28042. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  28043. return;
  28044. }
  28045. // VBO
  28046. var vertices = [];
  28047. vertices.push(1, 1);
  28048. vertices.push(-1, 1);
  28049. vertices.push(-1, -1);
  28050. vertices.push(1, -1);
  28051. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  28052. // Indices
  28053. var indices = [];
  28054. indices.push(0);
  28055. indices.push(1);
  28056. indices.push(2);
  28057. indices.push(0);
  28058. indices.push(2);
  28059. indices.push(3);
  28060. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  28061. };
  28062. // Methods
  28063. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  28064. var postProcesses = this._scene.activeCamera._postProcesses;
  28065. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28066. return false;
  28067. }
  28068. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  28069. return true;
  28070. };
  28071. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  28072. var engine = this._scene.getEngine();
  28073. for (var index = 0; index < postProcesses.length; index++) {
  28074. if (index < postProcesses.length - 1) {
  28075. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28076. }
  28077. else {
  28078. if (targetTexture) {
  28079. engine.bindFramebuffer(targetTexture);
  28080. }
  28081. else {
  28082. engine.restoreDefaultFramebuffer();
  28083. }
  28084. }
  28085. var pp = postProcesses[index];
  28086. var effect = pp.apply();
  28087. if (effect) {
  28088. pp.onBeforeRenderObservable.notifyObservers(effect);
  28089. // VBOs
  28090. this._prepareBuffers();
  28091. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28092. // Draw order
  28093. engine.draw(true, 0, 6);
  28094. pp.onAfterRenderObservable.notifyObservers(effect);
  28095. }
  28096. }
  28097. // Restore depth buffer
  28098. engine.setDepthBuffer(true);
  28099. engine.setDepthWrite(true);
  28100. };
  28101. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  28102. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  28103. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  28104. return;
  28105. }
  28106. var engine = this._scene.getEngine();
  28107. for (var index = 0, len = postProcesses.length; index < len; index++) {
  28108. if (index < len - 1) {
  28109. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  28110. }
  28111. else {
  28112. if (targetTexture) {
  28113. engine.bindFramebuffer(targetTexture, faceIndex);
  28114. }
  28115. else {
  28116. engine.restoreDefaultFramebuffer();
  28117. }
  28118. }
  28119. if (doNotPresent) {
  28120. break;
  28121. }
  28122. var pp = postProcesses[index];
  28123. var effect = pp.apply();
  28124. if (effect) {
  28125. pp.onBeforeRenderObservable.notifyObservers(effect);
  28126. // VBOs
  28127. this._prepareBuffers();
  28128. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28129. // Draw order
  28130. engine.draw(true, 0, 6);
  28131. pp.onAfterRenderObservable.notifyObservers(effect);
  28132. }
  28133. }
  28134. // Restore states
  28135. engine.setDepthBuffer(true);
  28136. engine.setDepthWrite(true);
  28137. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28138. };
  28139. PostProcessManager.prototype.dispose = function () {
  28140. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28141. if (buffer) {
  28142. buffer.dispose();
  28143. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28144. }
  28145. if (this._indexBuffer) {
  28146. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28147. this._indexBuffer = null;
  28148. }
  28149. };
  28150. return PostProcessManager;
  28151. }());
  28152. BABYLON.PostProcessManager = PostProcessManager;
  28153. })(BABYLON || (BABYLON = {}));
  28154. //# sourceMappingURL=babylon.postProcessManager.js.map
  28155. var BABYLON;
  28156. (function (BABYLON) {
  28157. var ShaderMaterial = (function (_super) {
  28158. __extends(ShaderMaterial, _super);
  28159. function ShaderMaterial(name, scene, shaderPath, options) {
  28160. var _this = _super.call(this, name, scene) || this;
  28161. _this._textures = {};
  28162. _this._textureArrays = {};
  28163. _this._floats = {};
  28164. _this._floatsArrays = {};
  28165. _this._colors3 = {};
  28166. _this._colors4 = {};
  28167. _this._vectors2 = {};
  28168. _this._vectors3 = {};
  28169. _this._vectors4 = {};
  28170. _this._matrices = {};
  28171. _this._matrices3x3 = {};
  28172. _this._matrices2x2 = {};
  28173. _this._vectors3Arrays = {};
  28174. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  28175. _this._shaderPath = shaderPath;
  28176. options.needAlphaBlending = options.needAlphaBlending || false;
  28177. options.needAlphaTesting = options.needAlphaTesting || false;
  28178. options.attributes = options.attributes || ["position", "normal", "uv"];
  28179. options.uniforms = options.uniforms || ["worldViewProjection"];
  28180. options.uniformBuffers = options.uniformBuffers || [];
  28181. options.samplers = options.samplers || [];
  28182. options.defines = options.defines || [];
  28183. _this._options = options;
  28184. return _this;
  28185. }
  28186. ShaderMaterial.prototype.getClassName = function () {
  28187. return "ShaderMaterial";
  28188. };
  28189. ShaderMaterial.prototype.needAlphaBlending = function () {
  28190. return this._options.needAlphaBlending;
  28191. };
  28192. ShaderMaterial.prototype.needAlphaTesting = function () {
  28193. return this._options.needAlphaTesting;
  28194. };
  28195. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  28196. if (this._options.uniforms.indexOf(uniformName) === -1) {
  28197. this._options.uniforms.push(uniformName);
  28198. }
  28199. };
  28200. ShaderMaterial.prototype.setTexture = function (name, texture) {
  28201. if (this._options.samplers.indexOf(name) === -1) {
  28202. this._options.samplers.push(name);
  28203. }
  28204. this._textures[name] = texture;
  28205. return this;
  28206. };
  28207. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  28208. if (this._options.samplers.indexOf(name) === -1) {
  28209. this._options.samplers.push(name);
  28210. }
  28211. this._checkUniform(name);
  28212. this._textureArrays[name] = textures;
  28213. return this;
  28214. };
  28215. ShaderMaterial.prototype.setFloat = function (name, value) {
  28216. this._checkUniform(name);
  28217. this._floats[name] = value;
  28218. return this;
  28219. };
  28220. ShaderMaterial.prototype.setFloats = function (name, value) {
  28221. this._checkUniform(name);
  28222. this._floatsArrays[name] = value;
  28223. return this;
  28224. };
  28225. ShaderMaterial.prototype.setColor3 = function (name, value) {
  28226. this._checkUniform(name);
  28227. this._colors3[name] = value;
  28228. return this;
  28229. };
  28230. ShaderMaterial.prototype.setColor4 = function (name, value) {
  28231. this._checkUniform(name);
  28232. this._colors4[name] = value;
  28233. return this;
  28234. };
  28235. ShaderMaterial.prototype.setVector2 = function (name, value) {
  28236. this._checkUniform(name);
  28237. this._vectors2[name] = value;
  28238. return this;
  28239. };
  28240. ShaderMaterial.prototype.setVector3 = function (name, value) {
  28241. this._checkUniform(name);
  28242. this._vectors3[name] = value;
  28243. return this;
  28244. };
  28245. ShaderMaterial.prototype.setVector4 = function (name, value) {
  28246. this._checkUniform(name);
  28247. this._vectors4[name] = value;
  28248. return this;
  28249. };
  28250. ShaderMaterial.prototype.setMatrix = function (name, value) {
  28251. this._checkUniform(name);
  28252. this._matrices[name] = value;
  28253. return this;
  28254. };
  28255. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  28256. this._checkUniform(name);
  28257. this._matrices3x3[name] = value;
  28258. return this;
  28259. };
  28260. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  28261. this._checkUniform(name);
  28262. this._matrices2x2[name] = value;
  28263. return this;
  28264. };
  28265. ShaderMaterial.prototype.setArray3 = function (name, value) {
  28266. this._checkUniform(name);
  28267. this._vectors3Arrays[name] = value;
  28268. return this;
  28269. };
  28270. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  28271. if (!mesh) {
  28272. return true;
  28273. }
  28274. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  28275. return false;
  28276. }
  28277. return false;
  28278. };
  28279. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  28280. var scene = this.getScene();
  28281. var engine = scene.getEngine();
  28282. if (!this.checkReadyOnEveryCall) {
  28283. if (this._renderId === scene.getRenderId()) {
  28284. if (this._checkCache(scene, mesh, useInstances)) {
  28285. return true;
  28286. }
  28287. }
  28288. }
  28289. // Instances
  28290. var defines = [];
  28291. var attribs = [];
  28292. var fallbacks = new BABYLON.EffectFallbacks();
  28293. if (useInstances) {
  28294. defines.push("#define INSTANCES");
  28295. }
  28296. for (var index = 0; index < this._options.defines.length; index++) {
  28297. defines.push(this._options.defines[index]);
  28298. }
  28299. for (var index = 0; index < this._options.attributes.length; index++) {
  28300. attribs.push(this._options.attributes[index]);
  28301. }
  28302. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28303. attribs.push(BABYLON.VertexBuffer.ColorKind);
  28304. defines.push("#define VERTEXCOLOR");
  28305. }
  28306. // Bones
  28307. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  28308. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28309. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28310. if (mesh.numBoneInfluencers > 4) {
  28311. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  28312. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  28313. }
  28314. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  28315. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28316. fallbacks.addCPUSkinningFallback(0, mesh);
  28317. }
  28318. else {
  28319. defines.push("#define NUM_BONE_INFLUENCERS 0");
  28320. }
  28321. // Textures
  28322. for (var name in this._textures) {
  28323. if (!this._textures[name].isReady()) {
  28324. return false;
  28325. }
  28326. }
  28327. // Alpha test
  28328. if (engine.getAlphaTesting()) {
  28329. defines.push("#define ALPHATEST");
  28330. }
  28331. var previousEffect = this._effect;
  28332. var join = defines.join("\n");
  28333. this._effect = engine.createEffect(this._shaderPath, {
  28334. attributes: attribs,
  28335. uniformsNames: this._options.uniforms,
  28336. uniformBuffersNames: this._options.uniformBuffers,
  28337. samplers: this._options.samplers,
  28338. defines: join,
  28339. fallbacks: fallbacks,
  28340. onCompiled: this.onCompiled,
  28341. onError: this.onError
  28342. }, engine);
  28343. if (!this._effect.isReady()) {
  28344. return false;
  28345. }
  28346. if (previousEffect !== this._effect) {
  28347. scene.resetCachedMaterial();
  28348. }
  28349. this._renderId = scene.getRenderId();
  28350. return true;
  28351. };
  28352. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  28353. var scene = this.getScene();
  28354. if (this._options.uniforms.indexOf("world") !== -1) {
  28355. this._effect.setMatrix("world", world);
  28356. }
  28357. if (this._options.uniforms.indexOf("worldView") !== -1) {
  28358. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  28359. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  28360. }
  28361. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  28362. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  28363. }
  28364. };
  28365. ShaderMaterial.prototype.bind = function (world, mesh) {
  28366. // Std values
  28367. this.bindOnlyWorldMatrix(world);
  28368. if (this.getScene().getCachedMaterial() !== this) {
  28369. if (this._options.uniforms.indexOf("view") !== -1) {
  28370. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  28371. }
  28372. if (this._options.uniforms.indexOf("projection") !== -1) {
  28373. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  28374. }
  28375. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  28376. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  28377. }
  28378. // Bones
  28379. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  28380. var name;
  28381. // Texture
  28382. for (name in this._textures) {
  28383. this._effect.setTexture(name, this._textures[name]);
  28384. }
  28385. // Texture arrays
  28386. for (name in this._textureArrays) {
  28387. this._effect.setTextureArray(name, this._textureArrays[name]);
  28388. }
  28389. // Float
  28390. for (name in this._floats) {
  28391. this._effect.setFloat(name, this._floats[name]);
  28392. }
  28393. // Float s
  28394. for (name in this._floatsArrays) {
  28395. this._effect.setArray(name, this._floatsArrays[name]);
  28396. }
  28397. // Color3
  28398. for (name in this._colors3) {
  28399. this._effect.setColor3(name, this._colors3[name]);
  28400. }
  28401. // Color4
  28402. for (name in this._colors4) {
  28403. var color = this._colors4[name];
  28404. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  28405. }
  28406. // Vector2
  28407. for (name in this._vectors2) {
  28408. this._effect.setVector2(name, this._vectors2[name]);
  28409. }
  28410. // Vector3
  28411. for (name in this._vectors3) {
  28412. this._effect.setVector3(name, this._vectors3[name]);
  28413. }
  28414. // Vector4
  28415. for (name in this._vectors4) {
  28416. this._effect.setVector4(name, this._vectors4[name]);
  28417. }
  28418. // Matrix
  28419. for (name in this._matrices) {
  28420. this._effect.setMatrix(name, this._matrices[name]);
  28421. }
  28422. // Matrix 3x3
  28423. for (name in this._matrices3x3) {
  28424. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  28425. }
  28426. // Matrix 2x2
  28427. for (name in this._matrices2x2) {
  28428. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  28429. }
  28430. // Vector3Array
  28431. for (name in this._vectors3Arrays) {
  28432. this._effect.setArray3(name, this._vectors3Arrays[name]);
  28433. }
  28434. }
  28435. this._afterBind(mesh);
  28436. };
  28437. ShaderMaterial.prototype.clone = function (name) {
  28438. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  28439. return newShaderMaterial;
  28440. };
  28441. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  28442. if (forceDisposeTextures) {
  28443. var name;
  28444. for (name in this._textures) {
  28445. this._textures[name].dispose();
  28446. }
  28447. for (name in this._textureArrays) {
  28448. var array = this._textureArrays[name];
  28449. for (var index = 0; index < array.length; index++) {
  28450. array[index].dispose();
  28451. }
  28452. }
  28453. }
  28454. this._textures = {};
  28455. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  28456. };
  28457. ShaderMaterial.prototype.serialize = function () {
  28458. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  28459. serializationObject.customType = "BABYLON.ShaderMaterial";
  28460. serializationObject.options = this._options;
  28461. serializationObject.shaderPath = this._shaderPath;
  28462. var name;
  28463. // Texture
  28464. serializationObject.textures = {};
  28465. for (name in this._textures) {
  28466. serializationObject.textures[name] = this._textures[name].serialize();
  28467. }
  28468. // Texture arrays
  28469. serializationObject.textureArrays = {};
  28470. for (name in this._textureArrays) {
  28471. serializationObject.textureArrays[name] = [];
  28472. var array = this._textureArrays[name];
  28473. for (var index = 0; index < array.length; index++) {
  28474. serializationObject.textureArrays[name].push(array[index].serialize());
  28475. }
  28476. }
  28477. // Float
  28478. serializationObject.floats = {};
  28479. for (name in this._floats) {
  28480. serializationObject.floats[name] = this._floats[name];
  28481. }
  28482. // Float s
  28483. serializationObject.floatArrays = {};
  28484. for (name in this._floatsArrays) {
  28485. serializationObject.floatArrays[name] = this._floatsArrays[name];
  28486. }
  28487. // Color3
  28488. serializationObject.colors3 = {};
  28489. for (name in this._colors3) {
  28490. serializationObject.colors3[name] = this._colors3[name].asArray();
  28491. }
  28492. // Color4
  28493. serializationObject.colors4 = {};
  28494. for (name in this._colors4) {
  28495. serializationObject.colors4[name] = this._colors4[name].asArray();
  28496. }
  28497. // Vector2
  28498. serializationObject.vectors2 = {};
  28499. for (name in this._vectors2) {
  28500. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  28501. }
  28502. // Vector3
  28503. serializationObject.vectors3 = {};
  28504. for (name in this._vectors3) {
  28505. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  28506. }
  28507. // Vector4
  28508. serializationObject.vectors4 = {};
  28509. for (name in this._vectors4) {
  28510. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  28511. }
  28512. // Matrix
  28513. serializationObject.matrices = {};
  28514. for (name in this._matrices) {
  28515. serializationObject.matrices[name] = this._matrices[name].asArray();
  28516. }
  28517. // Matrix 3x3
  28518. serializationObject.matrices3x3 = {};
  28519. for (name in this._matrices3x3) {
  28520. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  28521. }
  28522. // Matrix 2x2
  28523. serializationObject.matrices2x2 = {};
  28524. for (name in this._matrices2x2) {
  28525. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  28526. }
  28527. // Vector3Array
  28528. serializationObject.vectors3Arrays = {};
  28529. for (name in this._vectors3Arrays) {
  28530. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  28531. }
  28532. return serializationObject;
  28533. };
  28534. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  28535. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  28536. var name;
  28537. // Texture
  28538. for (name in source.textures) {
  28539. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  28540. }
  28541. // Texture arrays
  28542. for (name in source.textureArrays) {
  28543. var array = source.textureArrays[name];
  28544. var textureArray = new Array();
  28545. for (var index = 0; index < array.length; index++) {
  28546. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  28547. }
  28548. material.setTextureArray(name, textureArray);
  28549. }
  28550. // Float
  28551. for (name in source.floats) {
  28552. material.setFloat(name, source.floats[name]);
  28553. }
  28554. // Float s
  28555. for (name in source.floatsArrays) {
  28556. material.setFloats(name, source.floatsArrays[name]);
  28557. }
  28558. // Color3
  28559. for (name in source.colors3) {
  28560. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  28561. }
  28562. // Color4
  28563. for (name in source.colors4) {
  28564. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  28565. }
  28566. // Vector2
  28567. for (name in source.vectors2) {
  28568. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  28569. }
  28570. // Vector3
  28571. for (name in source.vectors3) {
  28572. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  28573. }
  28574. // Vector4
  28575. for (name in source.vectors4) {
  28576. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  28577. }
  28578. // Matrix
  28579. for (name in source.matrices) {
  28580. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  28581. }
  28582. // Matrix 3x3
  28583. for (name in source.matrices3x3) {
  28584. material.setMatrix3x3(name, source.matrices3x3[name]);
  28585. }
  28586. // Matrix 2x2
  28587. for (name in source.matrices2x2) {
  28588. material.setMatrix2x2(name, source.matrices2x2[name]);
  28589. }
  28590. // Vector3Array
  28591. for (name in source.vectors3Arrays) {
  28592. material.setArray3(name, source.vectors3Arrays[name]);
  28593. }
  28594. return material;
  28595. };
  28596. return ShaderMaterial;
  28597. }(BABYLON.Material));
  28598. BABYLON.ShaderMaterial = ShaderMaterial;
  28599. })(BABYLON || (BABYLON = {}));
  28600. //# sourceMappingURL=babylon.shaderMaterial.js.map
  28601. var BABYLON;
  28602. (function (BABYLON) {
  28603. var MeshBuilder = (function () {
  28604. function MeshBuilder() {
  28605. }
  28606. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  28607. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  28608. return BABYLON.Mesh.DOUBLESIDE;
  28609. }
  28610. if (orientation === undefined || orientation === null) {
  28611. return BABYLON.Mesh.FRONTSIDE;
  28612. }
  28613. return orientation;
  28614. };
  28615. /**
  28616. * Creates a box mesh.
  28617. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  28618. * The parameter `size` sets the size (float) of each box side (default 1).
  28619. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  28620. * 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).
  28621. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  28622. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28623. * 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).
  28624. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28625. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28626. */
  28627. MeshBuilder.CreateBox = function (name, options, scene) {
  28628. var box = new BABYLON.Mesh(name, scene);
  28629. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  28630. box.sideOrientation = options.sideOrientation;
  28631. var vertexData = BABYLON.VertexData.CreateBox(options);
  28632. vertexData.applyToMesh(box, options.updatable);
  28633. return box;
  28634. };
  28635. /**
  28636. * Creates a sphere mesh.
  28637. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  28638. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  28639. * 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`).
  28640. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  28641. * 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
  28642. * 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).
  28643. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28644. * 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).
  28645. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28646. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28647. */
  28648. MeshBuilder.CreateSphere = function (name, options, scene) {
  28649. var sphere = new BABYLON.Mesh(name, scene);
  28650. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  28651. sphere.sideOrientation = options.sideOrientation;
  28652. var vertexData = BABYLON.VertexData.CreateSphere(options);
  28653. vertexData.applyToMesh(sphere, options.updatable);
  28654. return sphere;
  28655. };
  28656. /**
  28657. * Creates a plane polygonal mesh. By default, this is a disc.
  28658. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  28659. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  28660. * 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.
  28661. * 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
  28662. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28663. * 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).
  28664. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28665. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28666. */
  28667. MeshBuilder.CreateDisc = function (name, options, scene) {
  28668. var disc = new BABYLON.Mesh(name, scene);
  28669. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  28670. disc.sideOrientation = options.sideOrientation;
  28671. var vertexData = BABYLON.VertexData.CreateDisc(options);
  28672. vertexData.applyToMesh(disc, options.updatable);
  28673. return disc;
  28674. };
  28675. /**
  28676. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  28677. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  28678. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  28679. * 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`).
  28680. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  28681. * 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.
  28682. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28683. * 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).
  28684. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28685. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28686. */
  28687. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  28688. var sphere = new BABYLON.Mesh(name, scene);
  28689. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  28690. sphere.sideOrientation = options.sideOrientation;
  28691. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  28692. vertexData.applyToMesh(sphere, options.updatable);
  28693. return sphere;
  28694. };
  28695. ;
  28696. /**
  28697. * Creates a ribbon mesh.
  28698. * 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.
  28699. *
  28700. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  28701. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  28702. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  28703. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  28704. * 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.
  28705. * 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.
  28706. * 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
  28707. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28708. * 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).
  28709. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28710. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  28711. * 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.
  28712. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  28713. * 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
  28714. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  28715. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  28716. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28717. */
  28718. MeshBuilder.CreateRibbon = function (name, options, scene) {
  28719. var pathArray = options.pathArray;
  28720. var closeArray = options.closeArray;
  28721. var closePath = options.closePath;
  28722. var offset = options.offset;
  28723. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  28724. var instance = options.instance;
  28725. var updatable = options.updatable;
  28726. if (instance) {
  28727. // positionFunction : ribbon case
  28728. // only pathArray and sideOrientation parameters are taken into account for positions update
  28729. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  28730. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  28731. var positionFunction = function (positions) {
  28732. var minlg = pathArray[0].length;
  28733. var i = 0;
  28734. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  28735. for (var si = 1; si <= ns; si++) {
  28736. for (var p = 0; p < pathArray.length; p++) {
  28737. var path = pathArray[p];
  28738. var l = path.length;
  28739. minlg = (minlg < l) ? minlg : l;
  28740. var j = 0;
  28741. while (j < minlg) {
  28742. positions[i] = path[j].x;
  28743. positions[i + 1] = path[j].y;
  28744. positions[i + 2] = path[j].z;
  28745. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  28746. BABYLON.Tmp.Vector3[0].x = path[j].x;
  28747. }
  28748. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  28749. BABYLON.Tmp.Vector3[1].x = path[j].x;
  28750. }
  28751. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  28752. BABYLON.Tmp.Vector3[0].y = path[j].y;
  28753. }
  28754. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  28755. BABYLON.Tmp.Vector3[1].y = path[j].y;
  28756. }
  28757. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  28758. BABYLON.Tmp.Vector3[0].z = path[j].z;
  28759. }
  28760. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  28761. BABYLON.Tmp.Vector3[1].z = path[j].z;
  28762. }
  28763. j++;
  28764. i += 3;
  28765. }
  28766. if (instance._closePath) {
  28767. positions[i] = path[0].x;
  28768. positions[i + 1] = path[0].y;
  28769. positions[i + 2] = path[0].z;
  28770. i += 3;
  28771. }
  28772. }
  28773. }
  28774. };
  28775. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28776. positionFunction(positions);
  28777. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  28778. instance._boundingInfo.update(instance._worldMatrix);
  28779. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28780. if (options.colors) {
  28781. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  28782. for (var c = 0; c < options.colors.length; c++) {
  28783. colors[c * 4] = options.colors[c].r;
  28784. colors[c * 4 + 1] = options.colors[c].g;
  28785. colors[c * 4 + 2] = options.colors[c].b;
  28786. colors[c * 4 + 3] = options.colors[c].a;
  28787. }
  28788. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  28789. }
  28790. if (options.uvs) {
  28791. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28792. for (var i = 0; i < options.uvs.length; i++) {
  28793. uvs[i * 2] = options.uvs[i].x;
  28794. uvs[i * 2 + 1] = options.uvs[i].y;
  28795. }
  28796. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  28797. }
  28798. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  28799. var indices = instance.getIndices();
  28800. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28801. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  28802. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  28803. if (instance._closePath) {
  28804. var indexFirst = 0;
  28805. var indexLast = 0;
  28806. for (var p = 0; p < pathArray.length; p++) {
  28807. indexFirst = instance._idx[p] * 3;
  28808. if (p + 1 < pathArray.length) {
  28809. indexLast = (instance._idx[p + 1] - 1) * 3;
  28810. }
  28811. else {
  28812. indexLast = normals.length - 3;
  28813. }
  28814. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  28815. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  28816. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  28817. normals[indexLast] = normals[indexFirst];
  28818. normals[indexLast + 1] = normals[indexFirst + 1];
  28819. normals[indexLast + 2] = normals[indexFirst + 2];
  28820. }
  28821. }
  28822. if (!(instance.areNormalsFrozen)) {
  28823. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28824. }
  28825. }
  28826. return instance;
  28827. }
  28828. else {
  28829. var ribbon = new BABYLON.Mesh(name, scene);
  28830. ribbon.sideOrientation = sideOrientation;
  28831. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  28832. if (closePath) {
  28833. ribbon._idx = vertexData._idx;
  28834. }
  28835. ribbon._closePath = closePath;
  28836. ribbon._closeArray = closeArray;
  28837. vertexData.applyToMesh(ribbon, updatable);
  28838. return ribbon;
  28839. }
  28840. };
  28841. /**
  28842. * Creates a cylinder or a cone mesh.
  28843. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  28844. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  28845. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  28846. * 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.
  28847. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  28848. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  28849. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  28850. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  28851. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  28852. * 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).
  28853. * 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
  28854. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  28855. * 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
  28856. * 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.
  28857. * If `enclose` is false, a ring surface is one element.
  28858. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  28859. * 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
  28860. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28861. * 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).
  28862. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28863. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28864. */
  28865. MeshBuilder.CreateCylinder = function (name, options, scene) {
  28866. var cylinder = new BABYLON.Mesh(name, scene);
  28867. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  28868. cylinder.sideOrientation = options.sideOrientation;
  28869. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  28870. vertexData.applyToMesh(cylinder, options.updatable);
  28871. return cylinder;
  28872. };
  28873. /**
  28874. * Creates a torus mesh.
  28875. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  28876. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  28877. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  28878. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  28879. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28880. * 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).
  28881. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28882. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28883. */
  28884. MeshBuilder.CreateTorus = function (name, options, scene) {
  28885. var torus = new BABYLON.Mesh(name, scene);
  28886. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  28887. torus.sideOrientation = options.sideOrientation;
  28888. var vertexData = BABYLON.VertexData.CreateTorus(options);
  28889. vertexData.applyToMesh(torus, options.updatable);
  28890. return torus;
  28891. };
  28892. /**
  28893. * Creates a torus knot mesh.
  28894. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  28895. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  28896. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  28897. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  28898. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  28899. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28900. * 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).
  28901. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28902. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28903. */
  28904. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  28905. var torusKnot = new BABYLON.Mesh(name, scene);
  28906. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  28907. torusKnot.sideOrientation = options.sideOrientation;
  28908. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  28909. vertexData.applyToMesh(torusKnot, options.updatable);
  28910. return torusKnot;
  28911. };
  28912. /**
  28913. * Creates a line system mesh.
  28914. * A line system is a pool of many lines gathered in a single mesh.
  28915. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  28916. * 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.
  28917. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  28918. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  28919. * 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
  28920. * 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
  28921. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  28922. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28923. */
  28924. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  28925. var instance = options.instance;
  28926. var lines = options.lines;
  28927. if (instance) {
  28928. var positionFunction = function (positions) {
  28929. var i = 0;
  28930. for (var l = 0; l < lines.length; l++) {
  28931. var points = lines[l];
  28932. for (var p = 0; p < points.length; p++) {
  28933. positions[i] = points[p].x;
  28934. positions[i + 1] = points[p].y;
  28935. positions[i + 2] = points[p].z;
  28936. i += 3;
  28937. }
  28938. }
  28939. };
  28940. instance.updateMeshPositions(positionFunction, false);
  28941. return instance;
  28942. }
  28943. // line system creation
  28944. var lineSystem = new BABYLON.LinesMesh(name, scene);
  28945. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  28946. vertexData.applyToMesh(lineSystem, options.updatable);
  28947. return lineSystem;
  28948. };
  28949. /**
  28950. * Creates a line mesh.
  28951. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  28952. * 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.
  28953. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  28954. * The parameter `points` is an array successive Vector3.
  28955. * 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
  28956. * When updating an instance, remember that only point positions can change, not the number of points.
  28957. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28958. */
  28959. MeshBuilder.CreateLines = function (name, options, scene) {
  28960. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  28961. return lines;
  28962. };
  28963. /**
  28964. * Creates a dashed line mesh.
  28965. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  28966. * 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.
  28967. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  28968. * The parameter `points` is an array successive Vector3.
  28969. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  28970. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  28971. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  28972. * 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
  28973. * When updating an instance, remember that only point positions can change, not the number of points.
  28974. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28975. */
  28976. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  28977. var points = options.points;
  28978. var instance = options.instance;
  28979. var gapSize = options.gapSize;
  28980. var dashNb = options.dashNb;
  28981. var dashSize = options.dashSize;
  28982. if (instance) {
  28983. var positionFunction = function (positions) {
  28984. var curvect = BABYLON.Vector3.Zero();
  28985. var nbSeg = positions.length / 6;
  28986. var lg = 0;
  28987. var nb = 0;
  28988. var shft = 0;
  28989. var dashshft = 0;
  28990. var curshft = 0;
  28991. var p = 0;
  28992. var i = 0;
  28993. var j = 0;
  28994. for (i = 0; i < points.length - 1; i++) {
  28995. points[i + 1].subtractToRef(points[i], curvect);
  28996. lg += curvect.length();
  28997. }
  28998. shft = lg / nbSeg;
  28999. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  29000. for (i = 0; i < points.length - 1; i++) {
  29001. points[i + 1].subtractToRef(points[i], curvect);
  29002. nb = Math.floor(curvect.length() / shft);
  29003. curvect.normalize();
  29004. j = 0;
  29005. while (j < nb && p < positions.length) {
  29006. curshft = shft * j;
  29007. positions[p] = points[i].x + curshft * curvect.x;
  29008. positions[p + 1] = points[i].y + curshft * curvect.y;
  29009. positions[p + 2] = points[i].z + curshft * curvect.z;
  29010. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  29011. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  29012. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  29013. p += 6;
  29014. j++;
  29015. }
  29016. }
  29017. while (p < positions.length) {
  29018. positions[p] = points[i].x;
  29019. positions[p + 1] = points[i].y;
  29020. positions[p + 2] = points[i].z;
  29021. p += 3;
  29022. }
  29023. };
  29024. instance.updateMeshPositions(positionFunction, false);
  29025. return instance;
  29026. }
  29027. // dashed lines creation
  29028. var dashedLines = new BABYLON.LinesMesh(name, scene);
  29029. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  29030. vertexData.applyToMesh(dashedLines, options.updatable);
  29031. dashedLines.dashSize = dashSize;
  29032. dashedLines.gapSize = gapSize;
  29033. return dashedLines;
  29034. };
  29035. /**
  29036. * Creates an extruded shape mesh.
  29037. * 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.
  29038. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  29039. *
  29040. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29041. * 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
  29042. * extruded along the Z axis.
  29043. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29044. * 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.
  29045. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29046. * 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
  29047. * 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
  29048. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29049. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29050. * 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).
  29051. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29052. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  29053. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29054. */
  29055. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  29056. var path = options.path;
  29057. var shape = options.shape;
  29058. var scale = options.scale || 1;
  29059. var rotation = options.rotation || 0;
  29060. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  29061. var updatable = options.updatable;
  29062. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  29063. var instance = options.instance;
  29064. var invertUV = options.invertUV || false;
  29065. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  29066. };
  29067. /**
  29068. * Creates an custom extruded shape mesh.
  29069. * 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.
  29070. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  29071. *
  29072. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29073. * 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
  29074. * extruded along the Z axis.
  29075. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29076. * 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
  29077. * and the distance of this point from the begining of the path :
  29078. * ```javascript
  29079. * var rotationFunction = function(i, distance) {
  29080. * // do things
  29081. * return rotationValue; }
  29082. * ```
  29083. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29084. * 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
  29085. * and the distance of this point from the begining of the path :
  29086. * ```javascript
  29087. * var scaleFunction = function(i, distance) {
  29088. * // do things
  29089. * return scaleValue;}
  29090. * ```
  29091. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29092. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29093. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29094. * 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
  29095. * 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
  29096. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29097. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29098. * 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).
  29099. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29100. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  29101. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29102. */
  29103. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  29104. var path = options.path;
  29105. var shape = options.shape;
  29106. var scaleFunction = options.scaleFunction || (function () { return 1; });
  29107. var rotationFunction = options.rotationFunction || (function () { return 0; });
  29108. var ribbonCloseArray = options.ribbonCloseArray || false;
  29109. var ribbonClosePath = options.ribbonClosePath || false;
  29110. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  29111. var updatable = options.updatable;
  29112. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  29113. var instance = options.instance;
  29114. var invertUV = options.invertUV || false;
  29115. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  29116. };
  29117. /**
  29118. * Creates lathe mesh.
  29119. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29120. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  29121. *
  29122. * 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
  29123. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29124. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29125. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29126. * 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.
  29127. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  29128. * 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
  29129. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29130. * 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).
  29131. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29132. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  29133. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29134. */
  29135. MeshBuilder.CreateLathe = function (name, options, scene) {
  29136. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  29137. var closed = (options.closed === undefined) ? true : options.closed;
  29138. var shape = options.shape;
  29139. var radius = options.radius || 1;
  29140. var tessellation = options.tessellation || 64;
  29141. var updatable = options.updatable;
  29142. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  29143. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  29144. var pi2 = Math.PI * 2;
  29145. var paths = new Array();
  29146. var invertUV = options.invertUV || false;
  29147. var i = 0;
  29148. var p = 0;
  29149. var step = pi2 / tessellation * arc;
  29150. var rotated;
  29151. var path = new Array();
  29152. ;
  29153. for (i = 0; i <= tessellation; i++) {
  29154. var path = [];
  29155. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  29156. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  29157. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  29158. }
  29159. for (p = 0; p < shape.length; p++) {
  29160. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  29161. path.push(rotated);
  29162. }
  29163. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  29164. 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));
  29165. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  29166. }
  29167. paths.push(path);
  29168. }
  29169. // lathe ribbon
  29170. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  29171. return lathe;
  29172. };
  29173. /**
  29174. * Creates a plane mesh.
  29175. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  29176. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29177. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  29178. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  29179. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29180. * 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).
  29181. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29182. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29183. */
  29184. MeshBuilder.CreatePlane = function (name, options, scene) {
  29185. var plane = new BABYLON.Mesh(name, scene);
  29186. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  29187. plane.sideOrientation = options.sideOrientation;
  29188. var vertexData = BABYLON.VertexData.CreatePlane(options);
  29189. vertexData.applyToMesh(plane, options.updatable);
  29190. if (options.sourcePlane) {
  29191. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  29192. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  29193. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  29194. plane.rotate(vectorProduct, product);
  29195. }
  29196. return plane;
  29197. };
  29198. /**
  29199. * Creates a ground mesh.
  29200. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  29201. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29202. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  29203. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29204. */
  29205. MeshBuilder.CreateGround = function (name, options, scene) {
  29206. var ground = new BABYLON.GroundMesh(name, scene);
  29207. ground._setReady(false);
  29208. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  29209. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  29210. ground._width = options.width || 1;
  29211. ground._height = options.height || 1;
  29212. ground._maxX = ground._width / 2;
  29213. ground._maxZ = ground._height / 2;
  29214. ground._minX = -ground._maxX;
  29215. ground._minZ = -ground._maxZ;
  29216. var vertexData = BABYLON.VertexData.CreateGround(options);
  29217. vertexData.applyToMesh(ground, options.updatable);
  29218. ground._setReady(true);
  29219. return ground;
  29220. };
  29221. /**
  29222. * Creates a tiled ground mesh.
  29223. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  29224. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  29225. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  29226. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  29227. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  29228. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  29229. * numbers of subdivisions on the ground width and height of each tile.
  29230. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29231. */
  29232. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  29233. var tiledGround = new BABYLON.Mesh(name, scene);
  29234. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  29235. vertexData.applyToMesh(tiledGround, options.updatable);
  29236. return tiledGround;
  29237. };
  29238. /**
  29239. * Creates a ground mesh from a height map.
  29240. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  29241. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  29242. * The parameter `url` sets the URL of the height map image resource.
  29243. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  29244. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  29245. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  29246. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  29247. * 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.
  29248. * 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).
  29249. * This function is passed the newly built mesh :
  29250. * ```javascript
  29251. * function(mesh) { // do things
  29252. * return; }
  29253. * ```
  29254. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29255. */
  29256. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  29257. var width = options.width || 10.0;
  29258. var height = options.height || 10.0;
  29259. var subdivisions = options.subdivisions || 1 | 0;
  29260. var minHeight = options.minHeight || 0.0;
  29261. var maxHeight = options.maxHeight || 10.0;
  29262. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  29263. var updatable = options.updatable;
  29264. var onReady = options.onReady;
  29265. var ground = new BABYLON.GroundMesh(name, scene);
  29266. ground._subdivisionsX = subdivisions;
  29267. ground._subdivisionsY = subdivisions;
  29268. ground._width = width;
  29269. ground._height = height;
  29270. ground._maxX = ground._width / 2.0;
  29271. ground._maxZ = ground._height / 2.0;
  29272. ground._minX = -ground._maxX;
  29273. ground._minZ = -ground._maxZ;
  29274. ground._setReady(false);
  29275. var onload = function (img) {
  29276. // Getting height map data
  29277. var canvas = document.createElement("canvas");
  29278. var context = canvas.getContext("2d");
  29279. var bufferWidth = img.width;
  29280. var bufferHeight = img.height;
  29281. canvas.width = bufferWidth;
  29282. canvas.height = bufferHeight;
  29283. context.drawImage(img, 0, 0);
  29284. // Create VertexData from map data
  29285. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  29286. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  29287. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  29288. width: width, height: height,
  29289. subdivisions: subdivisions,
  29290. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  29291. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  29292. });
  29293. vertexData.applyToMesh(ground, updatable);
  29294. ground._setReady(true);
  29295. //execute ready callback, if set
  29296. if (onReady) {
  29297. onReady(ground);
  29298. }
  29299. };
  29300. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  29301. return ground;
  29302. };
  29303. /**
  29304. * Creates a polygon mesh.
  29305. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29306. * 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.
  29307. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29308. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29309. * 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).
  29310. * Remember you can only change the shape positions, not their number when updating a polygon.
  29311. */
  29312. MeshBuilder.CreatePolygon = function (name, options, scene) {
  29313. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  29314. var shape = options.shape;
  29315. var holes = options.holes || [];
  29316. var depth = options.depth || 0;
  29317. var contours = [];
  29318. var hole = [];
  29319. for (var i = 0; i < shape.length; i++) {
  29320. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  29321. }
  29322. var epsilon = 0.00000001;
  29323. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  29324. contours.pop();
  29325. }
  29326. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  29327. for (var hNb = 0; hNb < holes.length; hNb++) {
  29328. hole = [];
  29329. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  29330. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  29331. }
  29332. polygonTriangulation.addHole(hole);
  29333. }
  29334. var polygon = polygonTriangulation.build(options.updatable, depth);
  29335. polygon.sideOrientation = options.sideOrientation;
  29336. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  29337. vertexData.applyToMesh(polygon, options.updatable);
  29338. return polygon;
  29339. };
  29340. ;
  29341. /**
  29342. * Creates an extruded polygon mesh, with depth in the Y direction.
  29343. * 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).
  29344. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  29345. */
  29346. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  29347. return MeshBuilder.CreatePolygon(name, options, scene);
  29348. };
  29349. ;
  29350. /**
  29351. * Creates a tube mesh.
  29352. * 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.
  29353. *
  29354. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  29355. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  29356. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  29357. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  29358. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  29359. * 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.
  29360. * It must return a radius value (positive float) :
  29361. * ```javascript
  29362. * var radiusFunction = function(i, distance) {
  29363. * // do things
  29364. * return radius; }
  29365. * ```
  29366. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  29367. * 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
  29368. * 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
  29369. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29370. * 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).
  29371. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29372. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  29373. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29374. */
  29375. MeshBuilder.CreateTube = function (name, options, scene) {
  29376. var path = options.path;
  29377. var radius = options.radius || 1.0;
  29378. var tessellation = options.tessellation || 64 | 0;
  29379. var radiusFunction = options.radiusFunction;
  29380. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  29381. var invertUV = options.invertUV || false;
  29382. var updatable = options.updatable;
  29383. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  29384. var instance = options.instance;
  29385. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  29386. // tube geometry
  29387. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  29388. var tangents = path3D.getTangents();
  29389. var normals = path3D.getNormals();
  29390. var distances = path3D.getDistances();
  29391. var pi2 = Math.PI * 2;
  29392. var step = pi2 / tessellation * arc;
  29393. var returnRadius = function () { return radius; };
  29394. var radiusFunctionFinal = radiusFunction || returnRadius;
  29395. var circlePath;
  29396. var rad;
  29397. var normal;
  29398. var rotated;
  29399. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  29400. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  29401. for (var i = 0; i < path.length; i++) {
  29402. rad = radiusFunctionFinal(i, distances[i]); // current radius
  29403. circlePath = Array(); // current circle array
  29404. normal = normals[i]; // current normal
  29405. for (var t = 0; t < tessellation; t++) {
  29406. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  29407. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  29408. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  29409. rotated.scaleInPlace(rad).addInPlace(path[i]);
  29410. circlePath[t] = rotated;
  29411. }
  29412. circlePaths[index] = circlePath;
  29413. index++;
  29414. }
  29415. // cap
  29416. var capPath = function (nbPoints, pathIndex) {
  29417. var pointCap = Array();
  29418. for (var i = 0; i < nbPoints; i++) {
  29419. pointCap.push(path[pathIndex]);
  29420. }
  29421. return pointCap;
  29422. };
  29423. switch (cap) {
  29424. case BABYLON.Mesh.NO_CAP:
  29425. break;
  29426. case BABYLON.Mesh.CAP_START:
  29427. circlePaths[0] = capPath(tessellation, 0);
  29428. circlePaths[1] = circlePaths[2].slice(0);
  29429. break;
  29430. case BABYLON.Mesh.CAP_END:
  29431. circlePaths[index] = circlePaths[index - 1].slice(0);
  29432. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  29433. break;
  29434. case BABYLON.Mesh.CAP_ALL:
  29435. circlePaths[0] = capPath(tessellation, 0);
  29436. circlePaths[1] = circlePaths[2].slice(0);
  29437. circlePaths[index] = circlePaths[index - 1].slice(0);
  29438. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  29439. break;
  29440. default:
  29441. break;
  29442. }
  29443. return circlePaths;
  29444. };
  29445. var path3D;
  29446. var pathArray;
  29447. if (instance) {
  29448. var arc = options.arc || instance.arc;
  29449. path3D = (instance.path3D).update(path);
  29450. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  29451. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  29452. instance.path3D = path3D;
  29453. instance.pathArray = pathArray;
  29454. instance.arc = arc;
  29455. return instance;
  29456. }
  29457. // tube creation
  29458. path3D = new BABYLON.Path3D(path);
  29459. var newPathArray = new Array();
  29460. cap = (cap < 0 || cap > 3) ? 0 : cap;
  29461. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  29462. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  29463. tube.pathArray = pathArray;
  29464. tube.path3D = path3D;
  29465. tube.tessellation = tessellation;
  29466. tube.cap = cap;
  29467. tube.arc = options.arc;
  29468. return tube;
  29469. };
  29470. /**
  29471. * Creates a polyhedron mesh.
  29472. *
  29473. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  29474. * 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
  29475. * to choose the wanted type.
  29476. * The parameter `size` (positive float, default 1) sets the polygon size.
  29477. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  29478. * 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`.
  29479. * 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
  29480. * 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)`).
  29481. * 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
  29482. * 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.
  29483. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29484. * 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).
  29485. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29486. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29487. */
  29488. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  29489. var polyhedron = new BABYLON.Mesh(name, scene);
  29490. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  29491. polyhedron.sideOrientation = options.sideOrientation;
  29492. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  29493. vertexData.applyToMesh(polyhedron, options.updatable);
  29494. return polyhedron;
  29495. };
  29496. /**
  29497. * Creates a decal mesh.
  29498. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  29499. * 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.
  29500. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  29501. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  29502. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  29503. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  29504. */
  29505. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  29506. var indices = sourceMesh.getIndices();
  29507. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29508. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29509. var position = options.position || BABYLON.Vector3.Zero();
  29510. var normal = options.normal || BABYLON.Vector3.Up();
  29511. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  29512. var angle = options.angle || 0;
  29513. // Getting correct rotation
  29514. if (!normal) {
  29515. var target = new BABYLON.Vector3(0, 0, 1);
  29516. var camera = sourceMesh.getScene().activeCamera;
  29517. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  29518. normal = camera.globalPosition.subtract(cameraWorldTarget);
  29519. }
  29520. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  29521. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  29522. var pitch = Math.atan2(normal.y, len);
  29523. // Matrix
  29524. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  29525. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  29526. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  29527. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  29528. var vertexData = new BABYLON.VertexData();
  29529. vertexData.indices = [];
  29530. vertexData.positions = [];
  29531. vertexData.normals = [];
  29532. vertexData.uvs = [];
  29533. var currentVertexDataIndex = 0;
  29534. var extractDecalVector3 = function (indexId) {
  29535. var vertexId = indices[indexId];
  29536. var result = new BABYLON.PositionNormalVertex();
  29537. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  29538. // Send vector to decal local world
  29539. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  29540. // Get normal
  29541. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  29542. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  29543. return result;
  29544. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  29545. var clip = function (vertices, axis) {
  29546. if (vertices.length === 0) {
  29547. return vertices;
  29548. }
  29549. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  29550. var clipVertices = function (v0, v1) {
  29551. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  29552. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  29553. };
  29554. var result = new Array();
  29555. for (var index = 0; index < vertices.length; index += 3) {
  29556. var v1Out;
  29557. var v2Out;
  29558. var v3Out;
  29559. var total = 0;
  29560. var nV1, nV2, nV3, nV4;
  29561. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  29562. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  29563. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  29564. v1Out = d1 > 0;
  29565. v2Out = d2 > 0;
  29566. v3Out = d3 > 0;
  29567. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  29568. switch (total) {
  29569. case 0:
  29570. result.push(vertices[index]);
  29571. result.push(vertices[index + 1]);
  29572. result.push(vertices[index + 2]);
  29573. break;
  29574. case 1:
  29575. if (v1Out) {
  29576. nV1 = vertices[index + 1];
  29577. nV2 = vertices[index + 2];
  29578. nV3 = clipVertices(vertices[index], nV1);
  29579. nV4 = clipVertices(vertices[index], nV2);
  29580. }
  29581. if (v2Out) {
  29582. nV1 = vertices[index];
  29583. nV2 = vertices[index + 2];
  29584. nV3 = clipVertices(vertices[index + 1], nV1);
  29585. nV4 = clipVertices(vertices[index + 1], nV2);
  29586. result.push(nV3);
  29587. result.push(nV2.clone());
  29588. result.push(nV1.clone());
  29589. result.push(nV2.clone());
  29590. result.push(nV3.clone());
  29591. result.push(nV4);
  29592. break;
  29593. }
  29594. if (v3Out) {
  29595. nV1 = vertices[index];
  29596. nV2 = vertices[index + 1];
  29597. nV3 = clipVertices(vertices[index + 2], nV1);
  29598. nV4 = clipVertices(vertices[index + 2], nV2);
  29599. }
  29600. result.push(nV1.clone());
  29601. result.push(nV2.clone());
  29602. result.push(nV3);
  29603. result.push(nV4);
  29604. result.push(nV3.clone());
  29605. result.push(nV2.clone());
  29606. break;
  29607. case 2:
  29608. if (!v1Out) {
  29609. nV1 = vertices[index].clone();
  29610. nV2 = clipVertices(nV1, vertices[index + 1]);
  29611. nV3 = clipVertices(nV1, vertices[index + 2]);
  29612. result.push(nV1);
  29613. result.push(nV2);
  29614. result.push(nV3);
  29615. }
  29616. if (!v2Out) {
  29617. nV1 = vertices[index + 1].clone();
  29618. nV2 = clipVertices(nV1, vertices[index + 2]);
  29619. nV3 = clipVertices(nV1, vertices[index]);
  29620. result.push(nV1);
  29621. result.push(nV2);
  29622. result.push(nV3);
  29623. }
  29624. if (!v3Out) {
  29625. nV1 = vertices[index + 2].clone();
  29626. nV2 = clipVertices(nV1, vertices[index]);
  29627. nV3 = clipVertices(nV1, vertices[index + 1]);
  29628. result.push(nV1);
  29629. result.push(nV2);
  29630. result.push(nV3);
  29631. }
  29632. break;
  29633. case 3:
  29634. break;
  29635. }
  29636. }
  29637. return result;
  29638. };
  29639. for (var index = 0; index < indices.length; index += 3) {
  29640. var faceVertices = new Array();
  29641. faceVertices.push(extractDecalVector3(index));
  29642. faceVertices.push(extractDecalVector3(index + 1));
  29643. faceVertices.push(extractDecalVector3(index + 2));
  29644. // Clip
  29645. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  29646. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  29647. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  29648. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  29649. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  29650. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  29651. if (faceVertices.length === 0) {
  29652. continue;
  29653. }
  29654. // Add UVs and get back to world
  29655. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  29656. var vertex = faceVertices[vIndex];
  29657. //TODO check for Int32Array | Uint32Array | Uint16Array
  29658. vertexData.indices.push(currentVertexDataIndex);
  29659. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  29660. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  29661. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  29662. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  29663. currentVertexDataIndex++;
  29664. }
  29665. }
  29666. // Return mesh
  29667. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  29668. vertexData.applyToMesh(decal);
  29669. decal.position = position.clone();
  29670. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  29671. return decal;
  29672. };
  29673. // Privates
  29674. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  29675. // extrusion geometry
  29676. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  29677. var tangents = path3D.getTangents();
  29678. var normals = path3D.getNormals();
  29679. var binormals = path3D.getBinormals();
  29680. var distances = path3D.getDistances();
  29681. var angle = 0;
  29682. var returnScale = function () { return scale; };
  29683. var returnRotation = function () { return rotation; };
  29684. var rotate = custom ? rotateFunction : returnRotation;
  29685. var scl = custom ? scaleFunction : returnScale;
  29686. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  29687. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  29688. for (var i = 0; i < curve.length; i++) {
  29689. var shapePath = new Array();
  29690. var angleStep = rotate(i, distances[i]);
  29691. var scaleRatio = scl(i, distances[i]);
  29692. for (var p = 0; p < shape.length; p++) {
  29693. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  29694. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  29695. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  29696. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  29697. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  29698. shapePath[p] = rotated;
  29699. }
  29700. shapePaths[index] = shapePath;
  29701. angle += angleStep;
  29702. index++;
  29703. }
  29704. // cap
  29705. var capPath = function (shapePath) {
  29706. var pointCap = Array();
  29707. var barycenter = BABYLON.Vector3.Zero();
  29708. var i;
  29709. for (i = 0; i < shapePath.length; i++) {
  29710. barycenter.addInPlace(shapePath[i]);
  29711. }
  29712. barycenter.scaleInPlace(1.0 / shapePath.length);
  29713. for (i = 0; i < shapePath.length; i++) {
  29714. pointCap.push(barycenter);
  29715. }
  29716. return pointCap;
  29717. };
  29718. switch (cap) {
  29719. case BABYLON.Mesh.NO_CAP:
  29720. break;
  29721. case BABYLON.Mesh.CAP_START:
  29722. shapePaths[0] = capPath(shapePaths[2]);
  29723. shapePaths[1] = shapePaths[2];
  29724. break;
  29725. case BABYLON.Mesh.CAP_END:
  29726. shapePaths[index] = shapePaths[index - 1];
  29727. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  29728. break;
  29729. case BABYLON.Mesh.CAP_ALL:
  29730. shapePaths[0] = capPath(shapePaths[2]);
  29731. shapePaths[1] = shapePaths[2];
  29732. shapePaths[index] = shapePaths[index - 1];
  29733. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  29734. break;
  29735. default:
  29736. break;
  29737. }
  29738. return shapePaths;
  29739. };
  29740. var path3D;
  29741. var pathArray;
  29742. if (instance) {
  29743. path3D = (instance.path3D).update(curve);
  29744. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  29745. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  29746. return instance;
  29747. }
  29748. // extruded shape creation
  29749. path3D = new BABYLON.Path3D(curve);
  29750. var newShapePaths = new Array();
  29751. cap = (cap < 0 || cap > 3) ? 0 : cap;
  29752. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  29753. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  29754. extrudedGeneric.pathArray = pathArray;
  29755. extrudedGeneric.path3D = path3D;
  29756. extrudedGeneric.cap = cap;
  29757. return extrudedGeneric;
  29758. };
  29759. return MeshBuilder;
  29760. }());
  29761. BABYLON.MeshBuilder = MeshBuilder;
  29762. })(BABYLON || (BABYLON = {}));
  29763. //# sourceMappingURL=babylon.meshBuilder.js.map
  29764. var BABYLON;
  29765. (function (BABYLON) {
  29766. var AnimationRange = (function () {
  29767. function AnimationRange(name, from, to) {
  29768. this.name = name;
  29769. this.from = from;
  29770. this.to = to;
  29771. }
  29772. AnimationRange.prototype.clone = function () {
  29773. return new AnimationRange(this.name, this.from, this.to);
  29774. };
  29775. return AnimationRange;
  29776. }());
  29777. BABYLON.AnimationRange = AnimationRange;
  29778. /**
  29779. * Composed of a frame, and an action function
  29780. */
  29781. var AnimationEvent = (function () {
  29782. function AnimationEvent(frame, action, onlyOnce) {
  29783. this.frame = frame;
  29784. this.action = action;
  29785. this.onlyOnce = onlyOnce;
  29786. this.isDone = false;
  29787. }
  29788. return AnimationEvent;
  29789. }());
  29790. BABYLON.AnimationEvent = AnimationEvent;
  29791. var PathCursor = (function () {
  29792. function PathCursor(path) {
  29793. this.path = path;
  29794. this._onchange = new Array();
  29795. this.value = 0;
  29796. this.animations = new Array();
  29797. }
  29798. PathCursor.prototype.getPoint = function () {
  29799. var point = this.path.getPointAtLengthPosition(this.value);
  29800. return new BABYLON.Vector3(point.x, 0, point.y);
  29801. };
  29802. PathCursor.prototype.moveAhead = function (step) {
  29803. if (step === void 0) { step = 0.002; }
  29804. this.move(step);
  29805. return this;
  29806. };
  29807. PathCursor.prototype.moveBack = function (step) {
  29808. if (step === void 0) { step = 0.002; }
  29809. this.move(-step);
  29810. return this;
  29811. };
  29812. PathCursor.prototype.move = function (step) {
  29813. if (Math.abs(step) > 1) {
  29814. throw "step size should be less than 1.";
  29815. }
  29816. this.value += step;
  29817. this.ensureLimits();
  29818. this.raiseOnChange();
  29819. return this;
  29820. };
  29821. PathCursor.prototype.ensureLimits = function () {
  29822. while (this.value > 1) {
  29823. this.value -= 1;
  29824. }
  29825. while (this.value < 0) {
  29826. this.value += 1;
  29827. }
  29828. return this;
  29829. };
  29830. // used by animation engine
  29831. PathCursor.prototype.markAsDirty = function (propertyName) {
  29832. this.ensureLimits();
  29833. this.raiseOnChange();
  29834. return this;
  29835. };
  29836. PathCursor.prototype.raiseOnChange = function () {
  29837. var _this = this;
  29838. this._onchange.forEach(function (f) { return f(_this); });
  29839. return this;
  29840. };
  29841. PathCursor.prototype.onchange = function (f) {
  29842. this._onchange.push(f);
  29843. return this;
  29844. };
  29845. return PathCursor;
  29846. }());
  29847. BABYLON.PathCursor = PathCursor;
  29848. var Animation = (function () {
  29849. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  29850. this.name = name;
  29851. this.targetProperty = targetProperty;
  29852. this.framePerSecond = framePerSecond;
  29853. this.dataType = dataType;
  29854. this.loopMode = loopMode;
  29855. this.enableBlending = enableBlending;
  29856. this._offsetsCache = {};
  29857. this._highLimitsCache = {};
  29858. this._stopped = false;
  29859. this._blendingFactor = 0;
  29860. // The set of event that will be linked to this animation
  29861. this._events = new Array();
  29862. this.allowMatricesInterpolation = false;
  29863. this.blendingSpeed = 0.01;
  29864. this._ranges = {};
  29865. this.targetPropertyPath = targetProperty.split(".");
  29866. this.dataType = dataType;
  29867. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  29868. }
  29869. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  29870. var dataType = undefined;
  29871. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  29872. dataType = Animation.ANIMATIONTYPE_FLOAT;
  29873. }
  29874. else if (from instanceof BABYLON.Quaternion) {
  29875. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  29876. }
  29877. else if (from instanceof BABYLON.Vector3) {
  29878. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  29879. }
  29880. else if (from instanceof BABYLON.Vector2) {
  29881. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  29882. }
  29883. else if (from instanceof BABYLON.Color3) {
  29884. dataType = Animation.ANIMATIONTYPE_COLOR3;
  29885. }
  29886. else if (from instanceof BABYLON.Size) {
  29887. dataType = Animation.ANIMATIONTYPE_SIZE;
  29888. }
  29889. if (dataType == undefined) {
  29890. return null;
  29891. }
  29892. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  29893. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  29894. animation.setKeys(keys);
  29895. if (easingFunction !== undefined) {
  29896. animation.setEasingFunction(easingFunction);
  29897. }
  29898. return animation;
  29899. };
  29900. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  29901. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  29902. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  29903. };
  29904. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  29905. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  29906. node.animations.push(animation);
  29907. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  29908. };
  29909. // Methods
  29910. /**
  29911. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29912. */
  29913. Animation.prototype.toString = function (fullDetails) {
  29914. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  29915. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  29916. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  29917. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  29918. if (fullDetails) {
  29919. ret += ", Ranges: {";
  29920. var first = true;
  29921. for (var name in this._ranges) {
  29922. if (first) {
  29923. ret += ", ";
  29924. first = false;
  29925. }
  29926. ret += name;
  29927. }
  29928. ret += "}";
  29929. }
  29930. return ret;
  29931. };
  29932. /**
  29933. * Add an event to this animation.
  29934. */
  29935. Animation.prototype.addEvent = function (event) {
  29936. this._events.push(event);
  29937. };
  29938. /**
  29939. * Remove all events found at the given frame
  29940. * @param frame
  29941. */
  29942. Animation.prototype.removeEvents = function (frame) {
  29943. for (var index = 0; index < this._events.length; index++) {
  29944. if (this._events[index].frame === frame) {
  29945. this._events.splice(index, 1);
  29946. index--;
  29947. }
  29948. }
  29949. };
  29950. Animation.prototype.createRange = function (name, from, to) {
  29951. // check name not already in use; could happen for bones after serialized
  29952. if (!this._ranges[name]) {
  29953. this._ranges[name] = new AnimationRange(name, from, to);
  29954. }
  29955. };
  29956. Animation.prototype.deleteRange = function (name, deleteFrames) {
  29957. if (deleteFrames === void 0) { deleteFrames = true; }
  29958. if (this._ranges[name]) {
  29959. if (deleteFrames) {
  29960. var from = this._ranges[name].from;
  29961. var to = this._ranges[name].to;
  29962. // this loop MUST go high to low for multiple splices to work
  29963. for (var key = this._keys.length - 1; key >= 0; key--) {
  29964. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  29965. this._keys.splice(key, 1);
  29966. }
  29967. }
  29968. }
  29969. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  29970. }
  29971. };
  29972. Animation.prototype.getRange = function (name) {
  29973. return this._ranges[name];
  29974. };
  29975. Animation.prototype.reset = function () {
  29976. this._offsetsCache = {};
  29977. this._highLimitsCache = {};
  29978. this.currentFrame = 0;
  29979. this._blendingFactor = 0;
  29980. this._originalBlendValue = null;
  29981. };
  29982. Animation.prototype.isStopped = function () {
  29983. return this._stopped;
  29984. };
  29985. Animation.prototype.getKeys = function () {
  29986. return this._keys;
  29987. };
  29988. Animation.prototype.getHighestFrame = function () {
  29989. var ret = 0;
  29990. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  29991. if (ret < this._keys[key].frame) {
  29992. ret = this._keys[key].frame;
  29993. }
  29994. }
  29995. return ret;
  29996. };
  29997. Animation.prototype.getEasingFunction = function () {
  29998. return this._easingFunction;
  29999. };
  30000. Animation.prototype.setEasingFunction = function (easingFunction) {
  30001. this._easingFunction = easingFunction;
  30002. };
  30003. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  30004. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  30005. };
  30006. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30007. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  30008. };
  30009. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  30010. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  30011. };
  30012. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30013. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  30014. };
  30015. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  30016. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  30017. };
  30018. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30019. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  30020. };
  30021. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  30022. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  30023. };
  30024. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  30025. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  30026. };
  30027. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  30028. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  30029. };
  30030. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  30031. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  30032. };
  30033. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  30034. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  30035. };
  30036. Animation.prototype.clone = function () {
  30037. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  30038. clone.enableBlending = this.enableBlending;
  30039. clone.blendingSpeed = this.blendingSpeed;
  30040. if (this._keys) {
  30041. clone.setKeys(this._keys);
  30042. }
  30043. if (this._ranges) {
  30044. clone._ranges = {};
  30045. for (var name in this._ranges) {
  30046. clone._ranges[name] = this._ranges[name].clone();
  30047. }
  30048. }
  30049. return clone;
  30050. };
  30051. Animation.prototype.setKeys = function (values) {
  30052. this._keys = values.slice(0);
  30053. this._offsetsCache = {};
  30054. this._highLimitsCache = {};
  30055. };
  30056. Animation.prototype._getKeyValue = function (value) {
  30057. if (typeof value === "function") {
  30058. return value();
  30059. }
  30060. return value;
  30061. };
  30062. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  30063. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  30064. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  30065. }
  30066. this.currentFrame = currentFrame;
  30067. // Try to get a hash to find the right key
  30068. 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));
  30069. if (this._keys[startKeyIndex].frame >= currentFrame) {
  30070. while (startKeyIndex - 1 >= 0 && this._keys[startKeyIndex].frame >= currentFrame) {
  30071. startKeyIndex--;
  30072. }
  30073. }
  30074. for (var key = startKeyIndex; key < this._keys.length; key++) {
  30075. var endKey = this._keys[key + 1];
  30076. if (endKey.frame >= currentFrame) {
  30077. var startKey = this._keys[key];
  30078. var startValue = this._getKeyValue(startKey.value);
  30079. var endValue = this._getKeyValue(endKey.value);
  30080. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  30081. var frameDelta = endKey.frame - startKey.frame;
  30082. // gradient : percent of currentFrame between the frame inf and the frame sup
  30083. var gradient = (currentFrame - startKey.frame) / frameDelta;
  30084. // check for easingFunction and correction of gradient
  30085. if (this._easingFunction != null) {
  30086. gradient = this._easingFunction.ease(gradient);
  30087. }
  30088. switch (this.dataType) {
  30089. // Float
  30090. case Animation.ANIMATIONTYPE_FLOAT:
  30091. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  30092. switch (loopMode) {
  30093. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30094. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30095. return floatValue;
  30096. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30097. return offsetValue * repeatCount + floatValue;
  30098. }
  30099. break;
  30100. // Quaternion
  30101. case Animation.ANIMATIONTYPE_QUATERNION:
  30102. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  30103. switch (loopMode) {
  30104. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30105. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30106. return quatValue;
  30107. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30108. return quatValue.add(offsetValue.scale(repeatCount));
  30109. }
  30110. return quatValue;
  30111. // Vector3
  30112. case Animation.ANIMATIONTYPE_VECTOR3:
  30113. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  30114. switch (loopMode) {
  30115. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30116. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30117. return vec3Value;
  30118. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30119. return vec3Value.add(offsetValue.scale(repeatCount));
  30120. }
  30121. // Vector2
  30122. case Animation.ANIMATIONTYPE_VECTOR2:
  30123. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  30124. switch (loopMode) {
  30125. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30126. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30127. return vec2Value;
  30128. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30129. return vec2Value.add(offsetValue.scale(repeatCount));
  30130. }
  30131. // Size
  30132. case Animation.ANIMATIONTYPE_SIZE:
  30133. switch (loopMode) {
  30134. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30135. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30136. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  30137. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30138. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30139. }
  30140. // Color3
  30141. case Animation.ANIMATIONTYPE_COLOR3:
  30142. switch (loopMode) {
  30143. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30144. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30145. return this.color3InterpolateFunction(startValue, endValue, gradient);
  30146. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30147. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30148. }
  30149. // Matrix
  30150. case Animation.ANIMATIONTYPE_MATRIX:
  30151. switch (loopMode) {
  30152. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30153. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30154. if (this.allowMatricesInterpolation) {
  30155. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  30156. }
  30157. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30158. return startValue;
  30159. }
  30160. default:
  30161. break;
  30162. }
  30163. break;
  30164. }
  30165. }
  30166. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  30167. };
  30168. Animation.prototype.setValue = function (currentValue, blend) {
  30169. if (blend === void 0) { blend = false; }
  30170. // Set value
  30171. var path;
  30172. var destination;
  30173. if (this.targetPropertyPath.length > 1) {
  30174. var property = this._target[this.targetPropertyPath[0]];
  30175. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  30176. property = property[this.targetPropertyPath[index]];
  30177. }
  30178. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  30179. destination = property;
  30180. }
  30181. else {
  30182. path = this.targetPropertyPath[0];
  30183. destination = this._target;
  30184. }
  30185. // Blending
  30186. if (this.enableBlending && this._blendingFactor <= 1.0) {
  30187. if (!this._originalBlendValue) {
  30188. if (destination[path].clone) {
  30189. this._originalBlendValue = destination[path].clone();
  30190. }
  30191. else {
  30192. this._originalBlendValue = destination[path];
  30193. }
  30194. }
  30195. if (this._originalBlendValue.prototype) {
  30196. if (this._originalBlendValue.prototype.Lerp) {
  30197. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  30198. }
  30199. else {
  30200. destination[path] = currentValue;
  30201. }
  30202. }
  30203. else if (this._originalBlendValue.m) {
  30204. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  30205. }
  30206. else {
  30207. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  30208. }
  30209. this._blendingFactor += this.blendingSpeed;
  30210. }
  30211. else {
  30212. destination[path] = currentValue;
  30213. }
  30214. if (this._target.markAsDirty) {
  30215. this._target.markAsDirty(this.targetProperty);
  30216. }
  30217. };
  30218. Animation.prototype.goToFrame = function (frame) {
  30219. if (frame < this._keys[0].frame) {
  30220. frame = this._keys[0].frame;
  30221. }
  30222. else if (frame > this._keys[this._keys.length - 1].frame) {
  30223. frame = this._keys[this._keys.length - 1].frame;
  30224. }
  30225. var currentValue = this._interpolate(frame, 0, this.loopMode);
  30226. this.setValue(currentValue);
  30227. };
  30228. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  30229. if (blend === void 0) { blend = false; }
  30230. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  30231. this._stopped = true;
  30232. return false;
  30233. }
  30234. var returnValue = true;
  30235. // Adding a start key at frame 0 if missing
  30236. if (this._keys[0].frame !== 0) {
  30237. var newKey = { frame: 0, value: this._keys[0].value };
  30238. this._keys.splice(0, 0, newKey);
  30239. }
  30240. // Check limits
  30241. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  30242. from = this._keys[0].frame;
  30243. }
  30244. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  30245. to = this._keys[this._keys.length - 1].frame;
  30246. }
  30247. //to and from cannot be the same key
  30248. if (from === to) {
  30249. from++;
  30250. }
  30251. // Compute ratio
  30252. var range = to - from;
  30253. var offsetValue;
  30254. // ratio represents the frame delta between from and to
  30255. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  30256. var highLimitValue = 0;
  30257. if (ratio > range && !loop) {
  30258. returnValue = false;
  30259. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  30260. }
  30261. else {
  30262. // Get max value if required
  30263. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  30264. var keyOffset = to.toString() + from.toString();
  30265. if (!this._offsetsCache[keyOffset]) {
  30266. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  30267. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  30268. switch (this.dataType) {
  30269. // Float
  30270. case Animation.ANIMATIONTYPE_FLOAT:
  30271. this._offsetsCache[keyOffset] = toValue - fromValue;
  30272. break;
  30273. // Quaternion
  30274. case Animation.ANIMATIONTYPE_QUATERNION:
  30275. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30276. break;
  30277. // Vector3
  30278. case Animation.ANIMATIONTYPE_VECTOR3:
  30279. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30280. // Vector2
  30281. case Animation.ANIMATIONTYPE_VECTOR2:
  30282. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30283. // Size
  30284. case Animation.ANIMATIONTYPE_SIZE:
  30285. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30286. // Color3
  30287. case Animation.ANIMATIONTYPE_COLOR3:
  30288. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30289. default:
  30290. break;
  30291. }
  30292. this._highLimitsCache[keyOffset] = toValue;
  30293. }
  30294. highLimitValue = this._highLimitsCache[keyOffset];
  30295. offsetValue = this._offsetsCache[keyOffset];
  30296. }
  30297. }
  30298. if (offsetValue === undefined) {
  30299. switch (this.dataType) {
  30300. // Float
  30301. case Animation.ANIMATIONTYPE_FLOAT:
  30302. offsetValue = 0;
  30303. break;
  30304. // Quaternion
  30305. case Animation.ANIMATIONTYPE_QUATERNION:
  30306. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  30307. break;
  30308. // Vector3
  30309. case Animation.ANIMATIONTYPE_VECTOR3:
  30310. offsetValue = BABYLON.Vector3.Zero();
  30311. break;
  30312. // Vector2
  30313. case Animation.ANIMATIONTYPE_VECTOR2:
  30314. offsetValue = BABYLON.Vector2.Zero();
  30315. break;
  30316. // Size
  30317. case Animation.ANIMATIONTYPE_SIZE:
  30318. offsetValue = BABYLON.Size.Zero();
  30319. break;
  30320. // Color3
  30321. case Animation.ANIMATIONTYPE_COLOR3:
  30322. offsetValue = BABYLON.Color3.Black();
  30323. }
  30324. }
  30325. // Compute value
  30326. var repeatCount = (ratio / range) >> 0;
  30327. var currentFrame = returnValue ? from + ratio % range : to;
  30328. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  30329. // Set value
  30330. this.setValue(currentValue);
  30331. // Check events
  30332. for (var index = 0; index < this._events.length; index++) {
  30333. if (currentFrame >= this._events[index].frame) {
  30334. var event = this._events[index];
  30335. if (!event.isDone) {
  30336. // If event should be done only once, remove it.
  30337. if (event.onlyOnce) {
  30338. this._events.splice(index, 1);
  30339. index--;
  30340. }
  30341. event.isDone = true;
  30342. event.action();
  30343. } // Don't do anything if the event has already be done.
  30344. }
  30345. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  30346. // reset event, the animation is looping
  30347. this._events[index].isDone = false;
  30348. }
  30349. }
  30350. if (!returnValue) {
  30351. this._stopped = true;
  30352. }
  30353. return returnValue;
  30354. };
  30355. Animation.prototype.serialize = function () {
  30356. var serializationObject = {};
  30357. serializationObject.name = this.name;
  30358. serializationObject.property = this.targetProperty;
  30359. serializationObject.framePerSecond = this.framePerSecond;
  30360. serializationObject.dataType = this.dataType;
  30361. serializationObject.loopBehavior = this.loopMode;
  30362. serializationObject.enableBlending = this.enableBlending;
  30363. serializationObject.blendingSpeed = this.blendingSpeed;
  30364. var dataType = this.dataType;
  30365. serializationObject.keys = [];
  30366. var keys = this.getKeys();
  30367. for (var index = 0; index < keys.length; index++) {
  30368. var animationKey = keys[index];
  30369. var key = {};
  30370. key.frame = animationKey.frame;
  30371. switch (dataType) {
  30372. case Animation.ANIMATIONTYPE_FLOAT:
  30373. key.values = [animationKey.value];
  30374. break;
  30375. case Animation.ANIMATIONTYPE_QUATERNION:
  30376. case Animation.ANIMATIONTYPE_MATRIX:
  30377. case Animation.ANIMATIONTYPE_VECTOR3:
  30378. case Animation.ANIMATIONTYPE_COLOR3:
  30379. key.values = animationKey.value.asArray();
  30380. break;
  30381. }
  30382. serializationObject.keys.push(key);
  30383. }
  30384. serializationObject.ranges = [];
  30385. for (var name in this._ranges) {
  30386. var range = {};
  30387. range.name = name;
  30388. range.from = this._ranges[name].from;
  30389. range.to = this._ranges[name].to;
  30390. serializationObject.ranges.push(range);
  30391. }
  30392. return serializationObject;
  30393. };
  30394. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  30395. get: function () {
  30396. return Animation._ANIMATIONTYPE_FLOAT;
  30397. },
  30398. enumerable: true,
  30399. configurable: true
  30400. });
  30401. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  30402. get: function () {
  30403. return Animation._ANIMATIONTYPE_VECTOR3;
  30404. },
  30405. enumerable: true,
  30406. configurable: true
  30407. });
  30408. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  30409. get: function () {
  30410. return Animation._ANIMATIONTYPE_VECTOR2;
  30411. },
  30412. enumerable: true,
  30413. configurable: true
  30414. });
  30415. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  30416. get: function () {
  30417. return Animation._ANIMATIONTYPE_SIZE;
  30418. },
  30419. enumerable: true,
  30420. configurable: true
  30421. });
  30422. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  30423. get: function () {
  30424. return Animation._ANIMATIONTYPE_QUATERNION;
  30425. },
  30426. enumerable: true,
  30427. configurable: true
  30428. });
  30429. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  30430. get: function () {
  30431. return Animation._ANIMATIONTYPE_MATRIX;
  30432. },
  30433. enumerable: true,
  30434. configurable: true
  30435. });
  30436. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  30437. get: function () {
  30438. return Animation._ANIMATIONTYPE_COLOR3;
  30439. },
  30440. enumerable: true,
  30441. configurable: true
  30442. });
  30443. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  30444. get: function () {
  30445. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  30446. },
  30447. enumerable: true,
  30448. configurable: true
  30449. });
  30450. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  30451. get: function () {
  30452. return Animation._ANIMATIONLOOPMODE_CYCLE;
  30453. },
  30454. enumerable: true,
  30455. configurable: true
  30456. });
  30457. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  30458. get: function () {
  30459. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  30460. },
  30461. enumerable: true,
  30462. configurable: true
  30463. });
  30464. Animation.Parse = function (parsedAnimation) {
  30465. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  30466. var dataType = parsedAnimation.dataType;
  30467. var keys = [];
  30468. var data;
  30469. var index;
  30470. if (parsedAnimation.enableBlending) {
  30471. animation.enableBlending = parsedAnimation.enableBlending;
  30472. }
  30473. if (parsedAnimation.blendingSpeed) {
  30474. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  30475. }
  30476. for (index = 0; index < parsedAnimation.keys.length; index++) {
  30477. var key = parsedAnimation.keys[index];
  30478. switch (dataType) {
  30479. case Animation.ANIMATIONTYPE_FLOAT:
  30480. data = key.values[0];
  30481. break;
  30482. case Animation.ANIMATIONTYPE_QUATERNION:
  30483. data = BABYLON.Quaternion.FromArray(key.values);
  30484. break;
  30485. case Animation.ANIMATIONTYPE_MATRIX:
  30486. data = BABYLON.Matrix.FromArray(key.values);
  30487. break;
  30488. case Animation.ANIMATIONTYPE_COLOR3:
  30489. data = BABYLON.Color3.FromArray(key.values);
  30490. break;
  30491. case Animation.ANIMATIONTYPE_VECTOR3:
  30492. default:
  30493. data = BABYLON.Vector3.FromArray(key.values);
  30494. break;
  30495. }
  30496. keys.push({
  30497. frame: key.frame,
  30498. value: data
  30499. });
  30500. }
  30501. animation.setKeys(keys);
  30502. if (parsedAnimation.ranges) {
  30503. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  30504. data = parsedAnimation.ranges[index];
  30505. animation.createRange(data.name, data.from, data.to);
  30506. }
  30507. }
  30508. return animation;
  30509. };
  30510. Animation.AppendSerializedAnimations = function (source, destination) {
  30511. if (source.animations) {
  30512. destination.animations = [];
  30513. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  30514. var animation = source.animations[animationIndex];
  30515. destination.animations.push(animation.serialize());
  30516. }
  30517. }
  30518. };
  30519. return Animation;
  30520. }());
  30521. // Statics
  30522. Animation._ANIMATIONTYPE_FLOAT = 0;
  30523. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  30524. Animation._ANIMATIONTYPE_QUATERNION = 2;
  30525. Animation._ANIMATIONTYPE_MATRIX = 3;
  30526. Animation._ANIMATIONTYPE_COLOR3 = 4;
  30527. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  30528. Animation._ANIMATIONTYPE_SIZE = 6;
  30529. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  30530. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  30531. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  30532. BABYLON.Animation = Animation;
  30533. })(BABYLON || (BABYLON = {}));
  30534. //# sourceMappingURL=babylon.animation.js.map
  30535. var BABYLON;
  30536. (function (BABYLON) {
  30537. var Animatable = (function () {
  30538. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  30539. if (fromFrame === void 0) { fromFrame = 0; }
  30540. if (toFrame === void 0) { toFrame = 100; }
  30541. if (loopAnimation === void 0) { loopAnimation = false; }
  30542. if (speedRatio === void 0) { speedRatio = 1.0; }
  30543. this.target = target;
  30544. this.fromFrame = fromFrame;
  30545. this.toFrame = toFrame;
  30546. this.loopAnimation = loopAnimation;
  30547. this.speedRatio = speedRatio;
  30548. this.onAnimationEnd = onAnimationEnd;
  30549. this._localDelayOffset = null;
  30550. this._pausedDelay = null;
  30551. this._animations = new Array();
  30552. this._paused = false;
  30553. this.animationStarted = false;
  30554. if (animations) {
  30555. this.appendAnimations(target, animations);
  30556. }
  30557. this._scene = scene;
  30558. scene._activeAnimatables.push(this);
  30559. }
  30560. // Methods
  30561. Animatable.prototype.getAnimations = function () {
  30562. return this._animations;
  30563. };
  30564. Animatable.prototype.appendAnimations = function (target, animations) {
  30565. for (var index = 0; index < animations.length; index++) {
  30566. var animation = animations[index];
  30567. animation._target = target;
  30568. this._animations.push(animation);
  30569. }
  30570. };
  30571. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  30572. var animations = this._animations;
  30573. for (var index = 0; index < animations.length; index++) {
  30574. if (animations[index].targetProperty === property) {
  30575. return animations[index];
  30576. }
  30577. }
  30578. return null;
  30579. };
  30580. Animatable.prototype.reset = function () {
  30581. var animations = this._animations;
  30582. for (var index = 0; index < animations.length; index++) {
  30583. animations[index].reset();
  30584. }
  30585. this._localDelayOffset = null;
  30586. this._pausedDelay = null;
  30587. };
  30588. Animatable.prototype.enableBlending = function (blendingSpeed) {
  30589. var animations = this._animations;
  30590. for (var index = 0; index < animations.length; index++) {
  30591. animations[index].enableBlending = true;
  30592. animations[index].blendingSpeed = blendingSpeed;
  30593. }
  30594. };
  30595. Animatable.prototype.disableBlending = function () {
  30596. var animations = this._animations;
  30597. for (var index = 0; index < animations.length; index++) {
  30598. animations[index].enableBlending = false;
  30599. }
  30600. };
  30601. Animatable.prototype.goToFrame = function (frame) {
  30602. var animations = this._animations;
  30603. if (animations[0]) {
  30604. var fps = animations[0].framePerSecond;
  30605. var currentFrame = animations[0].currentFrame;
  30606. var adjustTime = frame - currentFrame;
  30607. var delay = adjustTime * 1000 / fps;
  30608. this._localDelayOffset -= delay;
  30609. }
  30610. for (var index = 0; index < animations.length; index++) {
  30611. animations[index].goToFrame(frame);
  30612. }
  30613. };
  30614. Animatable.prototype.pause = function () {
  30615. if (this._paused) {
  30616. return;
  30617. }
  30618. this._paused = true;
  30619. };
  30620. Animatable.prototype.restart = function () {
  30621. this._paused = false;
  30622. };
  30623. Animatable.prototype.stop = function (animationName) {
  30624. if (animationName) {
  30625. var idx = this._scene._activeAnimatables.indexOf(this);
  30626. if (idx > -1) {
  30627. var animations = this._animations;
  30628. for (var index = animations.length - 1; index >= 0; index--) {
  30629. if (typeof animationName === "string" && animations[index].name != animationName) {
  30630. continue;
  30631. }
  30632. animations[index].reset();
  30633. animations.splice(index, 1);
  30634. }
  30635. if (animations.length == 0) {
  30636. this._scene._activeAnimatables.splice(idx, 1);
  30637. if (this.onAnimationEnd) {
  30638. this.onAnimationEnd();
  30639. }
  30640. }
  30641. }
  30642. }
  30643. else {
  30644. var index = this._scene._activeAnimatables.indexOf(this);
  30645. if (index > -1) {
  30646. this._scene._activeAnimatables.splice(index, 1);
  30647. var animations = this._animations;
  30648. for (var index = 0; index < animations.length; index++) {
  30649. animations[index].reset();
  30650. }
  30651. if (this.onAnimationEnd) {
  30652. this.onAnimationEnd();
  30653. }
  30654. }
  30655. }
  30656. };
  30657. Animatable.prototype._animate = function (delay) {
  30658. if (this._paused) {
  30659. this.animationStarted = false;
  30660. if (this._pausedDelay === null) {
  30661. this._pausedDelay = delay;
  30662. }
  30663. return true;
  30664. }
  30665. if (this._localDelayOffset === null) {
  30666. this._localDelayOffset = delay;
  30667. }
  30668. else if (this._pausedDelay !== null) {
  30669. this._localDelayOffset += delay - this._pausedDelay;
  30670. this._pausedDelay = null;
  30671. }
  30672. // Animating
  30673. var running = false;
  30674. var animations = this._animations;
  30675. var index;
  30676. for (index = 0; index < animations.length; index++) {
  30677. var animation = animations[index];
  30678. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  30679. running = running || isRunning;
  30680. }
  30681. this.animationStarted = running;
  30682. if (!running) {
  30683. // Remove from active animatables
  30684. index = this._scene._activeAnimatables.indexOf(this);
  30685. this._scene._activeAnimatables.splice(index, 1);
  30686. }
  30687. if (!running && this.onAnimationEnd) {
  30688. this.onAnimationEnd();
  30689. this.onAnimationEnd = null;
  30690. }
  30691. return running;
  30692. };
  30693. return Animatable;
  30694. }());
  30695. BABYLON.Animatable = Animatable;
  30696. })(BABYLON || (BABYLON = {}));
  30697. //# sourceMappingURL=babylon.animatable.js.map
  30698. var BABYLON;
  30699. (function (BABYLON) {
  30700. var EasingFunction = (function () {
  30701. function EasingFunction() {
  30702. // Properties
  30703. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  30704. }
  30705. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  30706. get: function () {
  30707. return EasingFunction._EASINGMODE_EASEIN;
  30708. },
  30709. enumerable: true,
  30710. configurable: true
  30711. });
  30712. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  30713. get: function () {
  30714. return EasingFunction._EASINGMODE_EASEOUT;
  30715. },
  30716. enumerable: true,
  30717. configurable: true
  30718. });
  30719. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  30720. get: function () {
  30721. return EasingFunction._EASINGMODE_EASEINOUT;
  30722. },
  30723. enumerable: true,
  30724. configurable: true
  30725. });
  30726. EasingFunction.prototype.setEasingMode = function (easingMode) {
  30727. var n = Math.min(Math.max(easingMode, 0), 2);
  30728. this._easingMode = n;
  30729. };
  30730. EasingFunction.prototype.getEasingMode = function () {
  30731. return this._easingMode;
  30732. };
  30733. EasingFunction.prototype.easeInCore = function (gradient) {
  30734. throw new Error('You must implement this method');
  30735. };
  30736. EasingFunction.prototype.ease = function (gradient) {
  30737. switch (this._easingMode) {
  30738. case EasingFunction.EASINGMODE_EASEIN:
  30739. return this.easeInCore(gradient);
  30740. case EasingFunction.EASINGMODE_EASEOUT:
  30741. return (1 - this.easeInCore(1 - gradient));
  30742. }
  30743. if (gradient >= 0.5) {
  30744. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  30745. }
  30746. return (this.easeInCore(gradient * 2) * 0.5);
  30747. };
  30748. return EasingFunction;
  30749. }());
  30750. //Statics
  30751. EasingFunction._EASINGMODE_EASEIN = 0;
  30752. EasingFunction._EASINGMODE_EASEOUT = 1;
  30753. EasingFunction._EASINGMODE_EASEINOUT = 2;
  30754. BABYLON.EasingFunction = EasingFunction;
  30755. var CircleEase = (function (_super) {
  30756. __extends(CircleEase, _super);
  30757. function CircleEase() {
  30758. return _super !== null && _super.apply(this, arguments) || this;
  30759. }
  30760. CircleEase.prototype.easeInCore = function (gradient) {
  30761. gradient = Math.max(0, Math.min(1, gradient));
  30762. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  30763. };
  30764. return CircleEase;
  30765. }(EasingFunction));
  30766. BABYLON.CircleEase = CircleEase;
  30767. var BackEase = (function (_super) {
  30768. __extends(BackEase, _super);
  30769. function BackEase(amplitude) {
  30770. if (amplitude === void 0) { amplitude = 1; }
  30771. var _this = _super.call(this) || this;
  30772. _this.amplitude = amplitude;
  30773. return _this;
  30774. }
  30775. BackEase.prototype.easeInCore = function (gradient) {
  30776. var num = Math.max(0, this.amplitude);
  30777. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  30778. };
  30779. return BackEase;
  30780. }(EasingFunction));
  30781. BABYLON.BackEase = BackEase;
  30782. var BounceEase = (function (_super) {
  30783. __extends(BounceEase, _super);
  30784. function BounceEase(bounces, bounciness) {
  30785. if (bounces === void 0) { bounces = 3; }
  30786. if (bounciness === void 0) { bounciness = 2; }
  30787. var _this = _super.call(this) || this;
  30788. _this.bounces = bounces;
  30789. _this.bounciness = bounciness;
  30790. return _this;
  30791. }
  30792. BounceEase.prototype.easeInCore = function (gradient) {
  30793. var y = Math.max(0.0, this.bounces);
  30794. var bounciness = this.bounciness;
  30795. if (bounciness <= 1.0) {
  30796. bounciness = 1.001;
  30797. }
  30798. var num9 = Math.pow(bounciness, y);
  30799. var num5 = 1.0 - bounciness;
  30800. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  30801. var num15 = gradient * num4;
  30802. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  30803. var num3 = Math.floor(num65);
  30804. var num13 = num3 + 1.0;
  30805. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  30806. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  30807. var num7 = (num8 + num12) * 0.5;
  30808. var num6 = gradient - num7;
  30809. var num2 = num7 - num8;
  30810. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  30811. };
  30812. return BounceEase;
  30813. }(EasingFunction));
  30814. BABYLON.BounceEase = BounceEase;
  30815. var CubicEase = (function (_super) {
  30816. __extends(CubicEase, _super);
  30817. function CubicEase() {
  30818. return _super !== null && _super.apply(this, arguments) || this;
  30819. }
  30820. CubicEase.prototype.easeInCore = function (gradient) {
  30821. return (gradient * gradient * gradient);
  30822. };
  30823. return CubicEase;
  30824. }(EasingFunction));
  30825. BABYLON.CubicEase = CubicEase;
  30826. var ElasticEase = (function (_super) {
  30827. __extends(ElasticEase, _super);
  30828. function ElasticEase(oscillations, springiness) {
  30829. if (oscillations === void 0) { oscillations = 3; }
  30830. if (springiness === void 0) { springiness = 3; }
  30831. var _this = _super.call(this) || this;
  30832. _this.oscillations = oscillations;
  30833. _this.springiness = springiness;
  30834. return _this;
  30835. }
  30836. ElasticEase.prototype.easeInCore = function (gradient) {
  30837. var num2;
  30838. var num3 = Math.max(0.0, this.oscillations);
  30839. var num = Math.max(0.0, this.springiness);
  30840. if (num == 0) {
  30841. num2 = gradient;
  30842. }
  30843. else {
  30844. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  30845. }
  30846. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  30847. };
  30848. return ElasticEase;
  30849. }(EasingFunction));
  30850. BABYLON.ElasticEase = ElasticEase;
  30851. var ExponentialEase = (function (_super) {
  30852. __extends(ExponentialEase, _super);
  30853. function ExponentialEase(exponent) {
  30854. if (exponent === void 0) { exponent = 2; }
  30855. var _this = _super.call(this) || this;
  30856. _this.exponent = exponent;
  30857. return _this;
  30858. }
  30859. ExponentialEase.prototype.easeInCore = function (gradient) {
  30860. if (this.exponent <= 0) {
  30861. return gradient;
  30862. }
  30863. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  30864. };
  30865. return ExponentialEase;
  30866. }(EasingFunction));
  30867. BABYLON.ExponentialEase = ExponentialEase;
  30868. var PowerEase = (function (_super) {
  30869. __extends(PowerEase, _super);
  30870. function PowerEase(power) {
  30871. if (power === void 0) { power = 2; }
  30872. var _this = _super.call(this) || this;
  30873. _this.power = power;
  30874. return _this;
  30875. }
  30876. PowerEase.prototype.easeInCore = function (gradient) {
  30877. var y = Math.max(0.0, this.power);
  30878. return Math.pow(gradient, y);
  30879. };
  30880. return PowerEase;
  30881. }(EasingFunction));
  30882. BABYLON.PowerEase = PowerEase;
  30883. var QuadraticEase = (function (_super) {
  30884. __extends(QuadraticEase, _super);
  30885. function QuadraticEase() {
  30886. return _super !== null && _super.apply(this, arguments) || this;
  30887. }
  30888. QuadraticEase.prototype.easeInCore = function (gradient) {
  30889. return (gradient * gradient);
  30890. };
  30891. return QuadraticEase;
  30892. }(EasingFunction));
  30893. BABYLON.QuadraticEase = QuadraticEase;
  30894. var QuarticEase = (function (_super) {
  30895. __extends(QuarticEase, _super);
  30896. function QuarticEase() {
  30897. return _super !== null && _super.apply(this, arguments) || this;
  30898. }
  30899. QuarticEase.prototype.easeInCore = function (gradient) {
  30900. return (gradient * gradient * gradient * gradient);
  30901. };
  30902. return QuarticEase;
  30903. }(EasingFunction));
  30904. BABYLON.QuarticEase = QuarticEase;
  30905. var QuinticEase = (function (_super) {
  30906. __extends(QuinticEase, _super);
  30907. function QuinticEase() {
  30908. return _super !== null && _super.apply(this, arguments) || this;
  30909. }
  30910. QuinticEase.prototype.easeInCore = function (gradient) {
  30911. return (gradient * gradient * gradient * gradient * gradient);
  30912. };
  30913. return QuinticEase;
  30914. }(EasingFunction));
  30915. BABYLON.QuinticEase = QuinticEase;
  30916. var SineEase = (function (_super) {
  30917. __extends(SineEase, _super);
  30918. function SineEase() {
  30919. return _super !== null && _super.apply(this, arguments) || this;
  30920. }
  30921. SineEase.prototype.easeInCore = function (gradient) {
  30922. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  30923. };
  30924. return SineEase;
  30925. }(EasingFunction));
  30926. BABYLON.SineEase = SineEase;
  30927. var BezierCurveEase = (function (_super) {
  30928. __extends(BezierCurveEase, _super);
  30929. function BezierCurveEase(x1, y1, x2, y2) {
  30930. if (x1 === void 0) { x1 = 0; }
  30931. if (y1 === void 0) { y1 = 0; }
  30932. if (x2 === void 0) { x2 = 1; }
  30933. if (y2 === void 0) { y2 = 1; }
  30934. var _this = _super.call(this) || this;
  30935. _this.x1 = x1;
  30936. _this.y1 = y1;
  30937. _this.x2 = x2;
  30938. _this.y2 = y2;
  30939. return _this;
  30940. }
  30941. BezierCurveEase.prototype.easeInCore = function (gradient) {
  30942. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  30943. };
  30944. return BezierCurveEase;
  30945. }(EasingFunction));
  30946. BABYLON.BezierCurveEase = BezierCurveEase;
  30947. })(BABYLON || (BABYLON = {}));
  30948. //# sourceMappingURL=babylon.easing.js.map
  30949. var BABYLON;
  30950. (function (BABYLON) {
  30951. BABYLON.CameraInputTypes = {};
  30952. var CameraInputsManager = (function () {
  30953. function CameraInputsManager(camera) {
  30954. this.attached = {};
  30955. this.camera = camera;
  30956. this.checkInputs = function () { };
  30957. }
  30958. CameraInputsManager.prototype.add = function (input) {
  30959. var type = input.getSimpleName();
  30960. if (this.attached[type]) {
  30961. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  30962. return;
  30963. }
  30964. this.attached[type] = input;
  30965. input.camera = this.camera;
  30966. //for checkInputs, we are dynamically creating a function
  30967. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  30968. if (input.checkInputs) {
  30969. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  30970. }
  30971. if (this.attachedElement) {
  30972. input.attachControl(this.attachedElement);
  30973. }
  30974. };
  30975. CameraInputsManager.prototype.remove = function (inputToRemove) {
  30976. for (var cam in this.attached) {
  30977. var input = this.attached[cam];
  30978. if (input === inputToRemove) {
  30979. input.detachControl(this.attachedElement);
  30980. delete this.attached[cam];
  30981. this.rebuildInputCheck();
  30982. }
  30983. }
  30984. };
  30985. CameraInputsManager.prototype.removeByType = function (inputType) {
  30986. for (var cam in this.attached) {
  30987. var input = this.attached[cam];
  30988. if (input.getTypeName() === inputType) {
  30989. input.detachControl(this.attachedElement);
  30990. delete this.attached[cam];
  30991. this.rebuildInputCheck();
  30992. }
  30993. }
  30994. };
  30995. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  30996. var current = this.checkInputs;
  30997. return function () {
  30998. current();
  30999. fn();
  31000. };
  31001. };
  31002. CameraInputsManager.prototype.attachInput = function (input) {
  31003. input.attachControl(this.attachedElement, this.noPreventDefault);
  31004. };
  31005. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  31006. if (this.attachedElement) {
  31007. return;
  31008. }
  31009. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  31010. this.attachedElement = element;
  31011. this.noPreventDefault = noPreventDefault;
  31012. for (var cam in this.attached) {
  31013. var input = this.attached[cam];
  31014. this.attached[cam].attachControl(element, noPreventDefault);
  31015. }
  31016. };
  31017. CameraInputsManager.prototype.detachElement = function (element) {
  31018. if (this.attachedElement !== element) {
  31019. return;
  31020. }
  31021. for (var cam in this.attached) {
  31022. var input = this.attached[cam];
  31023. this.attached[cam].detachControl(element);
  31024. }
  31025. this.attachedElement = null;
  31026. };
  31027. CameraInputsManager.prototype.rebuildInputCheck = function () {
  31028. this.checkInputs = function () { };
  31029. for (var cam in this.attached) {
  31030. var input = this.attached[cam];
  31031. if (input.checkInputs) {
  31032. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  31033. }
  31034. }
  31035. };
  31036. CameraInputsManager.prototype.clear = function () {
  31037. if (this.attachedElement) {
  31038. this.detachElement(this.attachedElement);
  31039. }
  31040. this.attached = {};
  31041. this.attachedElement = null;
  31042. this.checkInputs = function () { };
  31043. };
  31044. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  31045. var inputs = {};
  31046. for (var cam in this.attached) {
  31047. var input = this.attached[cam];
  31048. var res = BABYLON.SerializationHelper.Serialize(input);
  31049. inputs[input.getTypeName()] = res;
  31050. }
  31051. serializedCamera.inputsmgr = inputs;
  31052. };
  31053. CameraInputsManager.prototype.parse = function (parsedCamera) {
  31054. var parsedInputs = parsedCamera.inputsmgr;
  31055. if (parsedInputs) {
  31056. this.clear();
  31057. for (var n in parsedInputs) {
  31058. var construct = BABYLON.CameraInputTypes[n];
  31059. if (construct) {
  31060. var parsedinput = parsedInputs[n];
  31061. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  31062. this.add(input);
  31063. }
  31064. }
  31065. }
  31066. else {
  31067. //2016-03-08 this part is for managing backward compatibility
  31068. for (var n in this.attached) {
  31069. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  31070. if (construct) {
  31071. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  31072. this.remove(this.attached[n]);
  31073. this.add(input);
  31074. }
  31075. }
  31076. }
  31077. };
  31078. return CameraInputsManager;
  31079. }());
  31080. BABYLON.CameraInputsManager = CameraInputsManager;
  31081. })(BABYLON || (BABYLON = {}));
  31082. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  31083. /// <reference path="babylon.camera.ts" />
  31084. var BABYLON;
  31085. (function (BABYLON) {
  31086. var TargetCamera = (function (_super) {
  31087. __extends(TargetCamera, _super);
  31088. function TargetCamera(name, position, scene) {
  31089. var _this = _super.call(this, name, position, scene) || this;
  31090. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  31091. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  31092. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  31093. _this.speed = 2.0;
  31094. _this.noRotationConstraint = false;
  31095. _this.lockedTarget = null;
  31096. _this._currentTarget = BABYLON.Vector3.Zero();
  31097. _this._viewMatrix = BABYLON.Matrix.Zero();
  31098. _this._camMatrix = BABYLON.Matrix.Zero();
  31099. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  31100. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  31101. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  31102. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  31103. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  31104. _this._lookAtTemp = BABYLON.Matrix.Zero();
  31105. _this._tempMatrix = BABYLON.Matrix.Zero();
  31106. return _this;
  31107. }
  31108. TargetCamera.prototype.getFrontPosition = function (distance) {
  31109. var direction = this.getTarget().subtract(this.position);
  31110. direction.normalize();
  31111. direction.scaleInPlace(distance);
  31112. return this.globalPosition.add(direction);
  31113. };
  31114. TargetCamera.prototype._getLockedTargetPosition = function () {
  31115. if (!this.lockedTarget) {
  31116. return null;
  31117. }
  31118. if (this.lockedTarget.absolutePosition) {
  31119. this.lockedTarget.computeWorldMatrix();
  31120. }
  31121. return this.lockedTarget.absolutePosition || this.lockedTarget;
  31122. };
  31123. // Cache
  31124. TargetCamera.prototype._initCache = function () {
  31125. _super.prototype._initCache.call(this);
  31126. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31127. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31128. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31129. };
  31130. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  31131. if (!ignoreParentClass) {
  31132. _super.prototype._updateCache.call(this);
  31133. }
  31134. var lockedTargetPosition = this._getLockedTargetPosition();
  31135. if (!lockedTargetPosition) {
  31136. this._cache.lockedTarget = null;
  31137. }
  31138. else {
  31139. if (!this._cache.lockedTarget) {
  31140. this._cache.lockedTarget = lockedTargetPosition.clone();
  31141. }
  31142. else {
  31143. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  31144. }
  31145. }
  31146. this._cache.rotation.copyFrom(this.rotation);
  31147. if (this.rotationQuaternion)
  31148. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31149. };
  31150. // Synchronized
  31151. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  31152. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  31153. return false;
  31154. }
  31155. var lockedTargetPosition = this._getLockedTargetPosition();
  31156. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  31157. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  31158. };
  31159. // Methods
  31160. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  31161. var engine = this.getEngine();
  31162. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  31163. };
  31164. // Target
  31165. TargetCamera.prototype.setTarget = function (target) {
  31166. this.upVector.normalize();
  31167. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  31168. this._camMatrix.invert();
  31169. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  31170. var vDir = target.subtract(this.position);
  31171. if (vDir.x >= 0.0) {
  31172. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  31173. }
  31174. else {
  31175. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  31176. }
  31177. this.rotation.z = 0;
  31178. if (isNaN(this.rotation.x)) {
  31179. this.rotation.x = 0;
  31180. }
  31181. if (isNaN(this.rotation.y)) {
  31182. this.rotation.y = 0;
  31183. }
  31184. if (isNaN(this.rotation.z)) {
  31185. this.rotation.z = 0;
  31186. }
  31187. if (this.rotationQuaternion) {
  31188. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  31189. }
  31190. };
  31191. /**
  31192. * Return the current target position of the camera. This value is expressed in local space.
  31193. */
  31194. TargetCamera.prototype.getTarget = function () {
  31195. return this._currentTarget;
  31196. };
  31197. TargetCamera.prototype._decideIfNeedsToMove = function () {
  31198. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  31199. };
  31200. TargetCamera.prototype._updatePosition = function () {
  31201. if (this.parent) {
  31202. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  31203. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  31204. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  31205. return;
  31206. }
  31207. this.position.addInPlace(this.cameraDirection);
  31208. };
  31209. TargetCamera.prototype._checkInputs = function () {
  31210. var needToMove = this._decideIfNeedsToMove();
  31211. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  31212. // Move
  31213. if (needToMove) {
  31214. this._updatePosition();
  31215. }
  31216. // Rotate
  31217. if (needToRotate) {
  31218. this.rotation.x += this.cameraRotation.x;
  31219. this.rotation.y += this.cameraRotation.y;
  31220. //rotate, if quaternion is set and rotation was used
  31221. if (this.rotationQuaternion) {
  31222. var len = this.rotation.lengthSquared();
  31223. if (len) {
  31224. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  31225. }
  31226. }
  31227. if (!this.noRotationConstraint) {
  31228. var limit = (Math.PI / 2) * 0.95;
  31229. if (this.rotation.x > limit)
  31230. this.rotation.x = limit;
  31231. if (this.rotation.x < -limit)
  31232. this.rotation.x = -limit;
  31233. }
  31234. }
  31235. // Inertia
  31236. if (needToMove) {
  31237. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  31238. this.cameraDirection.x = 0;
  31239. }
  31240. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  31241. this.cameraDirection.y = 0;
  31242. }
  31243. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  31244. this.cameraDirection.z = 0;
  31245. }
  31246. this.cameraDirection.scaleInPlace(this.inertia);
  31247. }
  31248. if (needToRotate) {
  31249. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  31250. this.cameraRotation.x = 0;
  31251. }
  31252. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  31253. this.cameraRotation.y = 0;
  31254. }
  31255. this.cameraRotation.scaleInPlace(this.inertia);
  31256. }
  31257. _super.prototype._checkInputs.call(this);
  31258. };
  31259. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  31260. if (this.rotationQuaternion) {
  31261. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  31262. //update the up vector!
  31263. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  31264. }
  31265. else {
  31266. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  31267. }
  31268. };
  31269. TargetCamera.prototype._getViewMatrix = function () {
  31270. if (!this.lockedTarget) {
  31271. // Compute
  31272. this._updateCameraRotationMatrix();
  31273. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  31274. // Computing target and final matrix
  31275. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  31276. }
  31277. else {
  31278. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  31279. }
  31280. if (this.getScene().useRightHandedSystem) {
  31281. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  31282. }
  31283. else {
  31284. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  31285. }
  31286. return this._viewMatrix;
  31287. };
  31288. /**
  31289. * @override
  31290. * Override Camera.createRigCamera
  31291. */
  31292. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  31293. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  31294. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  31295. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  31296. if (!this.rotationQuaternion) {
  31297. this.rotationQuaternion = new BABYLON.Quaternion();
  31298. }
  31299. rigCamera._cameraRigParams = {};
  31300. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  31301. }
  31302. return rigCamera;
  31303. }
  31304. return null;
  31305. };
  31306. /**
  31307. * @override
  31308. * Override Camera._updateRigCameras
  31309. */
  31310. TargetCamera.prototype._updateRigCameras = function () {
  31311. var camLeft = this._rigCameras[0];
  31312. var camRight = this._rigCameras[1];
  31313. switch (this.cameraRigMode) {
  31314. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  31315. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  31316. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  31317. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  31318. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  31319. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  31320. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  31321. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  31322. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  31323. camLeft.setTarget(this.getTarget());
  31324. camRight.setTarget(this.getTarget());
  31325. break;
  31326. case BABYLON.Camera.RIG_MODE_VR:
  31327. if (camLeft.rotationQuaternion) {
  31328. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31329. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  31330. }
  31331. else {
  31332. camLeft.rotation.copyFrom(this.rotation);
  31333. camRight.rotation.copyFrom(this.rotation);
  31334. }
  31335. camLeft.position.copyFrom(this.position);
  31336. camRight.position.copyFrom(this.position);
  31337. break;
  31338. }
  31339. _super.prototype._updateRigCameras.call(this);
  31340. };
  31341. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  31342. if (!this._rigCamTransformMatrix) {
  31343. this._rigCamTransformMatrix = new BABYLON.Matrix();
  31344. }
  31345. var target = this.getTarget();
  31346. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  31347. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  31348. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  31349. };
  31350. TargetCamera.prototype.getClassName = function () {
  31351. return "TargetCamera";
  31352. };
  31353. return TargetCamera;
  31354. }(BABYLON.Camera));
  31355. __decorate([
  31356. BABYLON.serializeAsVector3()
  31357. ], TargetCamera.prototype, "rotation", void 0);
  31358. __decorate([
  31359. BABYLON.serialize()
  31360. ], TargetCamera.prototype, "speed", void 0);
  31361. __decorate([
  31362. BABYLON.serializeAsMeshReference("lockedTargetId")
  31363. ], TargetCamera.prototype, "lockedTarget", void 0);
  31364. BABYLON.TargetCamera = TargetCamera;
  31365. })(BABYLON || (BABYLON = {}));
  31366. //# sourceMappingURL=babylon.targetCamera.js.map
  31367. var BABYLON;
  31368. (function (BABYLON) {
  31369. var ArcRotateCameraKeyboardMoveInput = (function () {
  31370. function ArcRotateCameraKeyboardMoveInput() {
  31371. this._keys = [];
  31372. this.keysUp = [38];
  31373. this.keysDown = [40];
  31374. this.keysLeft = [37];
  31375. this.keysRight = [39];
  31376. }
  31377. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  31378. var _this = this;
  31379. element.tabIndex = 1;
  31380. this._onKeyDown = function (evt) {
  31381. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  31382. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  31383. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  31384. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  31385. var index = _this._keys.indexOf(evt.keyCode);
  31386. if (index === -1) {
  31387. _this._keys.push(evt.keyCode);
  31388. }
  31389. if (evt.preventDefault) {
  31390. if (!noPreventDefault) {
  31391. evt.preventDefault();
  31392. }
  31393. }
  31394. }
  31395. };
  31396. this._onKeyUp = function (evt) {
  31397. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  31398. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  31399. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  31400. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  31401. var index = _this._keys.indexOf(evt.keyCode);
  31402. if (index >= 0) {
  31403. _this._keys.splice(index, 1);
  31404. }
  31405. if (evt.preventDefault) {
  31406. if (!noPreventDefault) {
  31407. evt.preventDefault();
  31408. }
  31409. }
  31410. }
  31411. };
  31412. this._onLostFocus = function () {
  31413. _this._keys = [];
  31414. };
  31415. element.addEventListener("keydown", this._onKeyDown, false);
  31416. element.addEventListener("keyup", this._onKeyUp, false);
  31417. BABYLON.Tools.RegisterTopRootEvents([
  31418. { name: "blur", handler: this._onLostFocus }
  31419. ]);
  31420. };
  31421. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  31422. if (element) {
  31423. element.removeEventListener("keydown", this._onKeyDown);
  31424. element.removeEventListener("keyup", this._onKeyUp);
  31425. }
  31426. BABYLON.Tools.UnregisterTopRootEvents([
  31427. { name: "blur", handler: this._onLostFocus }
  31428. ]);
  31429. this._keys = [];
  31430. this._onKeyDown = null;
  31431. this._onKeyUp = null;
  31432. this._onLostFocus = null;
  31433. };
  31434. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  31435. if (this._onKeyDown) {
  31436. var camera = this.camera;
  31437. for (var index = 0; index < this._keys.length; index++) {
  31438. var keyCode = this._keys[index];
  31439. if (this.keysLeft.indexOf(keyCode) !== -1) {
  31440. camera.inertialAlphaOffset -= 0.01;
  31441. }
  31442. else if (this.keysUp.indexOf(keyCode) !== -1) {
  31443. camera.inertialBetaOffset -= 0.01;
  31444. }
  31445. else if (this.keysRight.indexOf(keyCode) !== -1) {
  31446. camera.inertialAlphaOffset += 0.01;
  31447. }
  31448. else if (this.keysDown.indexOf(keyCode) !== -1) {
  31449. camera.inertialBetaOffset += 0.01;
  31450. }
  31451. }
  31452. }
  31453. };
  31454. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  31455. return "ArcRotateCameraKeyboardMoveInput";
  31456. };
  31457. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  31458. return "keyboard";
  31459. };
  31460. return ArcRotateCameraKeyboardMoveInput;
  31461. }());
  31462. __decorate([
  31463. BABYLON.serialize()
  31464. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  31465. __decorate([
  31466. BABYLON.serialize()
  31467. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  31468. __decorate([
  31469. BABYLON.serialize()
  31470. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  31471. __decorate([
  31472. BABYLON.serialize()
  31473. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  31474. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  31475. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  31476. })(BABYLON || (BABYLON = {}));
  31477. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  31478. var BABYLON;
  31479. (function (BABYLON) {
  31480. var ArcRotateCameraMouseWheelInput = (function () {
  31481. function ArcRotateCameraMouseWheelInput() {
  31482. this.wheelPrecision = 3.0;
  31483. }
  31484. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  31485. var _this = this;
  31486. this._wheel = function (p, s) {
  31487. //sanity check - this should be a PointerWheel event.
  31488. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  31489. return;
  31490. var event = p.event;
  31491. var delta = 0;
  31492. if (event.wheelDelta) {
  31493. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  31494. }
  31495. else if (event.detail) {
  31496. delta = -event.detail / _this.wheelPrecision;
  31497. }
  31498. if (delta)
  31499. _this.camera.inertialRadiusOffset += delta;
  31500. if (event.preventDefault) {
  31501. if (!noPreventDefault) {
  31502. event.preventDefault();
  31503. }
  31504. }
  31505. };
  31506. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  31507. };
  31508. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  31509. if (this._observer && element) {
  31510. this.camera.getScene().onPointerObservable.remove(this._observer);
  31511. this._observer = null;
  31512. this._wheel = null;
  31513. }
  31514. };
  31515. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  31516. return "ArcRotateCameraMouseWheelInput";
  31517. };
  31518. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  31519. return "mousewheel";
  31520. };
  31521. return ArcRotateCameraMouseWheelInput;
  31522. }());
  31523. __decorate([
  31524. BABYLON.serialize()
  31525. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  31526. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  31527. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  31528. })(BABYLON || (BABYLON = {}));
  31529. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  31530. var BABYLON;
  31531. (function (BABYLON) {
  31532. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  31533. var ArcRotateCameraPointersInput = (function () {
  31534. function ArcRotateCameraPointersInput() {
  31535. this.buttons = [0, 1, 2];
  31536. this.angularSensibilityX = 1000.0;
  31537. this.angularSensibilityY = 1000.0;
  31538. this.pinchPrecision = 6.0;
  31539. this.panningSensibility = 50.0;
  31540. this._isPanClick = false;
  31541. this.pinchInwards = true;
  31542. }
  31543. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  31544. var _this = this;
  31545. var engine = this.camera.getEngine();
  31546. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  31547. var pointA, pointB;
  31548. var previousPinchDistance = 0;
  31549. this._pointerInput = function (p, s) {
  31550. var evt = p.event;
  31551. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  31552. return;
  31553. }
  31554. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  31555. try {
  31556. evt.srcElement.setPointerCapture(evt.pointerId);
  31557. }
  31558. catch (e) {
  31559. //Nothing to do with the error. Execution will continue.
  31560. }
  31561. // Manage panning with pan button click
  31562. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  31563. // manage pointers
  31564. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  31565. if (pointA === undefined) {
  31566. pointA = cacheSoloPointer;
  31567. }
  31568. else if (pointB === undefined) {
  31569. pointB = cacheSoloPointer;
  31570. }
  31571. if (!noPreventDefault) {
  31572. evt.preventDefault();
  31573. element.focus();
  31574. }
  31575. }
  31576. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  31577. try {
  31578. evt.srcElement.releasePointerCapture(evt.pointerId);
  31579. }
  31580. catch (e) {
  31581. //Nothing to do with the error.
  31582. }
  31583. cacheSoloPointer = null;
  31584. previousPinchDistance = 0;
  31585. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  31586. //but emptying completly pointers collection is required to fix a bug on iPhone :
  31587. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  31588. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  31589. pointA = pointB = undefined;
  31590. if (!noPreventDefault) {
  31591. evt.preventDefault();
  31592. }
  31593. }
  31594. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  31595. if (!noPreventDefault) {
  31596. evt.preventDefault();
  31597. }
  31598. // One button down
  31599. if (pointA && pointB === undefined) {
  31600. if (_this.panningSensibility !== 0 &&
  31601. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  31602. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  31603. _this.camera
  31604. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  31605. _this.camera
  31606. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  31607. }
  31608. else {
  31609. var offsetX = evt.clientX - cacheSoloPointer.x;
  31610. var offsetY = evt.clientY - cacheSoloPointer.y;
  31611. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  31612. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  31613. }
  31614. cacheSoloPointer.x = evt.clientX;
  31615. cacheSoloPointer.y = evt.clientY;
  31616. }
  31617. else if (pointA && pointB) {
  31618. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  31619. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  31620. ed.x = evt.clientX;
  31621. ed.y = evt.clientY;
  31622. var direction = _this.pinchInwards ? 1 : -1;
  31623. var distX = pointA.x - pointB.x;
  31624. var distY = pointA.y - pointB.y;
  31625. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  31626. if (previousPinchDistance === 0) {
  31627. previousPinchDistance = pinchSquaredDistance;
  31628. return;
  31629. }
  31630. if (pinchSquaredDistance !== previousPinchDistance) {
  31631. _this.camera
  31632. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  31633. (_this.pinchPrecision *
  31634. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  31635. direction);
  31636. previousPinchDistance = pinchSquaredDistance;
  31637. }
  31638. }
  31639. }
  31640. };
  31641. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  31642. this._onContextMenu = function (evt) {
  31643. evt.preventDefault();
  31644. };
  31645. if (!this.camera._useCtrlForPanning) {
  31646. element.addEventListener("contextmenu", this._onContextMenu, false);
  31647. }
  31648. this._onLostFocus = function () {
  31649. //this._keys = [];
  31650. pointA = pointB = undefined;
  31651. previousPinchDistance = 0;
  31652. cacheSoloPointer = null;
  31653. };
  31654. this._onMouseMove = function (evt) {
  31655. if (!engine.isPointerLock) {
  31656. return;
  31657. }
  31658. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  31659. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  31660. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  31661. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  31662. if (!noPreventDefault) {
  31663. evt.preventDefault();
  31664. }
  31665. };
  31666. this._onGestureStart = function (e) {
  31667. if (window.MSGesture === undefined) {
  31668. return;
  31669. }
  31670. if (!_this._MSGestureHandler) {
  31671. _this._MSGestureHandler = new MSGesture();
  31672. _this._MSGestureHandler.target = element;
  31673. }
  31674. _this._MSGestureHandler.addPointer(e.pointerId);
  31675. };
  31676. this._onGesture = function (e) {
  31677. _this.camera.radius *= e.scale;
  31678. if (e.preventDefault) {
  31679. if (!noPreventDefault) {
  31680. e.stopPropagation();
  31681. e.preventDefault();
  31682. }
  31683. }
  31684. };
  31685. element.addEventListener("mousemove", this._onMouseMove, false);
  31686. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  31687. element.addEventListener("MSGestureChange", this._onGesture, false);
  31688. BABYLON.Tools.RegisterTopRootEvents([
  31689. { name: "blur", handler: this._onLostFocus }
  31690. ]);
  31691. };
  31692. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  31693. if (element && this._observer) {
  31694. this.camera.getScene().onPointerObservable.remove(this._observer);
  31695. this._observer = null;
  31696. element.removeEventListener("contextmenu", this._onContextMenu);
  31697. element.removeEventListener("mousemove", this._onMouseMove);
  31698. element.removeEventListener("MSPointerDown", this._onGestureStart);
  31699. element.removeEventListener("MSGestureChange", this._onGesture);
  31700. this._isPanClick = false;
  31701. this.pinchInwards = true;
  31702. this._onMouseMove = null;
  31703. this._onGestureStart = null;
  31704. this._onGesture = null;
  31705. this._MSGestureHandler = null;
  31706. this._onLostFocus = null;
  31707. this._onContextMenu = null;
  31708. }
  31709. BABYLON.Tools.UnregisterTopRootEvents([
  31710. { name: "blur", handler: this._onLostFocus }
  31711. ]);
  31712. };
  31713. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  31714. return "ArcRotateCameraPointersInput";
  31715. };
  31716. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  31717. return "pointers";
  31718. };
  31719. return ArcRotateCameraPointersInput;
  31720. }());
  31721. __decorate([
  31722. BABYLON.serialize()
  31723. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  31724. __decorate([
  31725. BABYLON.serialize()
  31726. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  31727. __decorate([
  31728. BABYLON.serialize()
  31729. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  31730. __decorate([
  31731. BABYLON.serialize()
  31732. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  31733. __decorate([
  31734. BABYLON.serialize()
  31735. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  31736. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  31737. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  31738. })(BABYLON || (BABYLON = {}));
  31739. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  31740. /// <reference path="babylon.targetCamera.ts" />
  31741. /// <reference path="..\Tools\babylon.tools.ts" />
  31742. var BABYLON;
  31743. (function (BABYLON) {
  31744. var ArcRotateCamera = (function (_super) {
  31745. __extends(ArcRotateCamera, _super);
  31746. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  31747. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  31748. _this.inertialAlphaOffset = 0;
  31749. _this.inertialBetaOffset = 0;
  31750. _this.inertialRadiusOffset = 0;
  31751. _this.lowerAlphaLimit = null;
  31752. _this.upperAlphaLimit = null;
  31753. _this.lowerBetaLimit = 0.01;
  31754. _this.upperBetaLimit = Math.PI;
  31755. _this.lowerRadiusLimit = null;
  31756. _this.upperRadiusLimit = null;
  31757. _this.inertialPanningX = 0;
  31758. _this.inertialPanningY = 0;
  31759. _this.panningInertia = 0.9;
  31760. //-- end properties for backward compatibility for inputs
  31761. _this.zoomOnFactor = 1;
  31762. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  31763. _this.allowUpsideDown = true;
  31764. _this._viewMatrix = new BABYLON.Matrix();
  31765. // Panning
  31766. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  31767. _this.checkCollisions = false;
  31768. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  31769. _this._previousPosition = BABYLON.Vector3.Zero();
  31770. _this._collisionVelocity = BABYLON.Vector3.Zero();
  31771. _this._newPosition = BABYLON.Vector3.Zero();
  31772. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  31773. if (collidedMesh === void 0) { collidedMesh = null; }
  31774. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  31775. newPosition.multiplyInPlace(_this._collider.radius);
  31776. }
  31777. if (!collidedMesh) {
  31778. _this._previousPosition.copyFrom(_this.position);
  31779. }
  31780. else {
  31781. _this.setPosition(newPosition);
  31782. if (_this.onCollide) {
  31783. _this.onCollide(collidedMesh);
  31784. }
  31785. }
  31786. // Recompute because of constraints
  31787. var cosa = Math.cos(_this.alpha);
  31788. var sina = Math.sin(_this.alpha);
  31789. var cosb = Math.cos(_this.beta);
  31790. var sinb = Math.sin(_this.beta);
  31791. if (sinb === 0) {
  31792. sinb = 0.0001;
  31793. }
  31794. var target = _this._getTargetPosition();
  31795. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  31796. _this.position.copyFrom(_this._newPosition);
  31797. var up = _this.upVector;
  31798. if (_this.allowUpsideDown && _this.beta < 0) {
  31799. up = up.clone();
  31800. up = up.negate();
  31801. }
  31802. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  31803. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  31804. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  31805. _this._collisionTriggered = false;
  31806. };
  31807. _this._target = BABYLON.Vector3.Zero();
  31808. if (target) {
  31809. _this.setTarget(target);
  31810. }
  31811. _this.alpha = alpha;
  31812. _this.beta = beta;
  31813. _this.radius = radius;
  31814. _this.getViewMatrix();
  31815. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  31816. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  31817. return _this;
  31818. }
  31819. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  31820. get: function () {
  31821. return this._target;
  31822. },
  31823. set: function (value) {
  31824. this.setTarget(value);
  31825. },
  31826. enumerable: true,
  31827. configurable: true
  31828. });
  31829. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  31830. //-- begin properties for backward compatibility for inputs
  31831. get: function () {
  31832. var pointers = this.inputs.attached["pointers"];
  31833. if (pointers)
  31834. return pointers.angularSensibilityX;
  31835. },
  31836. set: function (value) {
  31837. var pointers = this.inputs.attached["pointers"];
  31838. if (pointers) {
  31839. pointers.angularSensibilityX = value;
  31840. }
  31841. },
  31842. enumerable: true,
  31843. configurable: true
  31844. });
  31845. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  31846. get: function () {
  31847. var pointers = this.inputs.attached["pointers"];
  31848. if (pointers)
  31849. return pointers.angularSensibilityY;
  31850. },
  31851. set: function (value) {
  31852. var pointers = this.inputs.attached["pointers"];
  31853. if (pointers) {
  31854. pointers.angularSensibilityY = value;
  31855. }
  31856. },
  31857. enumerable: true,
  31858. configurable: true
  31859. });
  31860. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  31861. get: function () {
  31862. var pointers = this.inputs.attached["pointers"];
  31863. if (pointers)
  31864. return pointers.pinchPrecision;
  31865. },
  31866. set: function (value) {
  31867. var pointers = this.inputs.attached["pointers"];
  31868. if (pointers) {
  31869. pointers.pinchPrecision = value;
  31870. }
  31871. },
  31872. enumerable: true,
  31873. configurable: true
  31874. });
  31875. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  31876. get: function () {
  31877. var pointers = this.inputs.attached["pointers"];
  31878. if (pointers)
  31879. return pointers.panningSensibility;
  31880. },
  31881. set: function (value) {
  31882. var pointers = this.inputs.attached["pointers"];
  31883. if (pointers) {
  31884. pointers.panningSensibility = value;
  31885. }
  31886. },
  31887. enumerable: true,
  31888. configurable: true
  31889. });
  31890. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  31891. get: function () {
  31892. var keyboard = this.inputs.attached["keyboard"];
  31893. if (keyboard)
  31894. return keyboard.keysUp;
  31895. },
  31896. set: function (value) {
  31897. var keyboard = this.inputs.attached["keyboard"];
  31898. if (keyboard)
  31899. keyboard.keysUp = value;
  31900. },
  31901. enumerable: true,
  31902. configurable: true
  31903. });
  31904. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  31905. get: function () {
  31906. var keyboard = this.inputs.attached["keyboard"];
  31907. if (keyboard)
  31908. return keyboard.keysDown;
  31909. },
  31910. set: function (value) {
  31911. var keyboard = this.inputs.attached["keyboard"];
  31912. if (keyboard)
  31913. keyboard.keysDown = value;
  31914. },
  31915. enumerable: true,
  31916. configurable: true
  31917. });
  31918. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  31919. get: function () {
  31920. var keyboard = this.inputs.attached["keyboard"];
  31921. if (keyboard)
  31922. return keyboard.keysLeft;
  31923. },
  31924. set: function (value) {
  31925. var keyboard = this.inputs.attached["keyboard"];
  31926. if (keyboard)
  31927. keyboard.keysLeft = value;
  31928. },
  31929. enumerable: true,
  31930. configurable: true
  31931. });
  31932. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  31933. get: function () {
  31934. var keyboard = this.inputs.attached["keyboard"];
  31935. if (keyboard)
  31936. return keyboard.keysRight;
  31937. },
  31938. set: function (value) {
  31939. var keyboard = this.inputs.attached["keyboard"];
  31940. if (keyboard)
  31941. keyboard.keysRight = value;
  31942. },
  31943. enumerable: true,
  31944. configurable: true
  31945. });
  31946. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  31947. get: function () {
  31948. var mousewheel = this.inputs.attached["mousewheel"];
  31949. if (mousewheel)
  31950. return mousewheel.wheelPrecision;
  31951. },
  31952. set: function (value) {
  31953. var mousewheel = this.inputs.attached["mousewheel"];
  31954. if (mousewheel)
  31955. mousewheel.wheelPrecision = value;
  31956. },
  31957. enumerable: true,
  31958. configurable: true
  31959. });
  31960. // Cache
  31961. ArcRotateCamera.prototype._initCache = function () {
  31962. _super.prototype._initCache.call(this);
  31963. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31964. this._cache.alpha = undefined;
  31965. this._cache.beta = undefined;
  31966. this._cache.radius = undefined;
  31967. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  31968. };
  31969. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  31970. if (!ignoreParentClass) {
  31971. _super.prototype._updateCache.call(this);
  31972. }
  31973. this._cache._target.copyFrom(this._getTargetPosition());
  31974. this._cache.alpha = this.alpha;
  31975. this._cache.beta = this.beta;
  31976. this._cache.radius = this.radius;
  31977. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  31978. };
  31979. ArcRotateCamera.prototype._getTargetPosition = function () {
  31980. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  31981. var pos = this._targetHost.getAbsolutePosition();
  31982. if (this._targetBoundingCenter) {
  31983. pos.addToRef(this._targetBoundingCenter, this._target);
  31984. }
  31985. else {
  31986. this._target.copyFrom(pos);
  31987. }
  31988. }
  31989. return this._target;
  31990. };
  31991. // Synchronized
  31992. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  31993. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  31994. return false;
  31995. return this._cache._target.equals(this._target)
  31996. && this._cache.alpha === this.alpha
  31997. && this._cache.beta === this.beta
  31998. && this._cache.radius === this.radius
  31999. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  32000. };
  32001. // Methods
  32002. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  32003. var _this = this;
  32004. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  32005. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  32006. this._useCtrlForPanning = useCtrlForPanning;
  32007. this._panningMouseButton = panningMouseButton;
  32008. this.inputs.attachElement(element, noPreventDefault);
  32009. this._reset = function () {
  32010. _this.inertialAlphaOffset = 0;
  32011. _this.inertialBetaOffset = 0;
  32012. _this.inertialRadiusOffset = 0;
  32013. };
  32014. };
  32015. ArcRotateCamera.prototype.detachControl = function (element) {
  32016. this.inputs.detachElement(element);
  32017. if (this._reset) {
  32018. this._reset();
  32019. }
  32020. };
  32021. ArcRotateCamera.prototype._checkInputs = function () {
  32022. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  32023. if (this._collisionTriggered) {
  32024. return;
  32025. }
  32026. this.inputs.checkInputs();
  32027. // Inertia
  32028. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  32029. if (this.getScene().useRightHandedSystem) {
  32030. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  32031. }
  32032. else {
  32033. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  32034. }
  32035. this.beta += this.inertialBetaOffset;
  32036. this.radius -= this.inertialRadiusOffset;
  32037. this.inertialAlphaOffset *= this.inertia;
  32038. this.inertialBetaOffset *= this.inertia;
  32039. this.inertialRadiusOffset *= this.inertia;
  32040. if (Math.abs(this.inertialAlphaOffset) < this.speed * BABYLON.Epsilon)
  32041. this.inertialAlphaOffset = 0;
  32042. if (Math.abs(this.inertialBetaOffset) < this.speed * BABYLON.Epsilon)
  32043. this.inertialBetaOffset = 0;
  32044. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  32045. this.inertialRadiusOffset = 0;
  32046. }
  32047. // Panning inertia
  32048. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  32049. if (!this._localDirection) {
  32050. this._localDirection = BABYLON.Vector3.Zero();
  32051. this._transformedDirection = BABYLON.Vector3.Zero();
  32052. }
  32053. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  32054. this._localDirection.multiplyInPlace(this.panningAxis);
  32055. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  32056. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  32057. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  32058. if (!this.panningAxis.y) {
  32059. this._transformedDirection.y = 0;
  32060. }
  32061. if (!this._targetHost) {
  32062. this._target.addInPlace(this._transformedDirection);
  32063. }
  32064. this.inertialPanningX *= this.panningInertia;
  32065. this.inertialPanningY *= this.panningInertia;
  32066. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  32067. this.inertialPanningX = 0;
  32068. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  32069. this.inertialPanningY = 0;
  32070. }
  32071. // Limits
  32072. this._checkLimits();
  32073. _super.prototype._checkInputs.call(this);
  32074. };
  32075. ArcRotateCamera.prototype._checkLimits = function () {
  32076. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  32077. if (this.allowUpsideDown && this.beta > Math.PI) {
  32078. this.beta = this.beta - (2 * Math.PI);
  32079. }
  32080. }
  32081. else {
  32082. if (this.beta < this.lowerBetaLimit) {
  32083. this.beta = this.lowerBetaLimit;
  32084. }
  32085. }
  32086. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  32087. if (this.allowUpsideDown && this.beta < -Math.PI) {
  32088. this.beta = this.beta + (2 * Math.PI);
  32089. }
  32090. }
  32091. else {
  32092. if (this.beta > this.upperBetaLimit) {
  32093. this.beta = this.upperBetaLimit;
  32094. }
  32095. }
  32096. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  32097. this.alpha = this.lowerAlphaLimit;
  32098. }
  32099. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  32100. this.alpha = this.upperAlphaLimit;
  32101. }
  32102. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  32103. this.radius = this.lowerRadiusLimit;
  32104. }
  32105. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  32106. this.radius = this.upperRadiusLimit;
  32107. }
  32108. };
  32109. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  32110. var radiusv3 = this.position.subtract(this._getTargetPosition());
  32111. this.radius = radiusv3.length();
  32112. // Alpha
  32113. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  32114. if (radiusv3.z < 0) {
  32115. this.alpha = 2 * Math.PI - this.alpha;
  32116. }
  32117. // Beta
  32118. this.beta = Math.acos(radiusv3.y / this.radius);
  32119. this._checkLimits();
  32120. };
  32121. ArcRotateCamera.prototype.setPosition = function (position) {
  32122. if (this.position.equals(position)) {
  32123. return;
  32124. }
  32125. this.position.copyFrom(position);
  32126. this.rebuildAnglesAndRadius();
  32127. };
  32128. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  32129. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  32130. if (allowSamePosition === void 0) { allowSamePosition = false; }
  32131. if (target.getBoundingInfo) {
  32132. if (toBoundingCenter) {
  32133. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  32134. }
  32135. else {
  32136. this._targetBoundingCenter = null;
  32137. }
  32138. this._targetHost = target;
  32139. this._target = this._getTargetPosition();
  32140. }
  32141. else {
  32142. var newTarget = target;
  32143. var currentTarget = this._getTargetPosition();
  32144. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  32145. return;
  32146. }
  32147. this._target = newTarget;
  32148. this._targetBoundingCenter = null;
  32149. }
  32150. this.rebuildAnglesAndRadius();
  32151. };
  32152. ArcRotateCamera.prototype._getViewMatrix = function () {
  32153. // Compute
  32154. var cosa = Math.cos(this.alpha);
  32155. var sina = Math.sin(this.alpha);
  32156. var cosb = Math.cos(this.beta);
  32157. var sinb = Math.sin(this.beta);
  32158. if (sinb === 0) {
  32159. sinb = 0.0001;
  32160. }
  32161. var target = this._getTargetPosition();
  32162. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  32163. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  32164. if (!this._collider) {
  32165. this._collider = new BABYLON.Collider();
  32166. }
  32167. this._collider.radius = this.collisionRadius;
  32168. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  32169. this._collisionTriggered = true;
  32170. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  32171. }
  32172. else {
  32173. this.position.copyFrom(this._newPosition);
  32174. var up = this.upVector;
  32175. if (this.allowUpsideDown && sinb < 0) {
  32176. up = up.clone();
  32177. up = up.negate();
  32178. }
  32179. if (this.getScene().useRightHandedSystem) {
  32180. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  32181. }
  32182. else {
  32183. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  32184. }
  32185. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  32186. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  32187. }
  32188. this._currentTarget = target;
  32189. return this._viewMatrix;
  32190. };
  32191. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  32192. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  32193. meshes = meshes || this.getScene().meshes;
  32194. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  32195. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  32196. this.radius = distance * this.zoomOnFactor;
  32197. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  32198. };
  32199. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  32200. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  32201. var meshesOrMinMaxVector;
  32202. var distance;
  32203. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  32204. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  32205. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  32206. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  32207. }
  32208. else {
  32209. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  32210. distance = meshesOrMinMaxVectorAndDistance.distance;
  32211. }
  32212. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  32213. if (!doNotUpdateMaxZ) {
  32214. this.maxZ = distance * 2;
  32215. }
  32216. };
  32217. /**
  32218. * @override
  32219. * Override Camera.createRigCamera
  32220. */
  32221. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  32222. var alphaShift;
  32223. switch (this.cameraRigMode) {
  32224. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  32225. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  32226. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  32227. case BABYLON.Camera.RIG_MODE_VR:
  32228. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  32229. break;
  32230. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  32231. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  32232. break;
  32233. }
  32234. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  32235. rigCam._cameraRigParams = {};
  32236. return rigCam;
  32237. };
  32238. /**
  32239. * @override
  32240. * Override Camera._updateRigCameras
  32241. */
  32242. ArcRotateCamera.prototype._updateRigCameras = function () {
  32243. var camLeft = this._rigCameras[0];
  32244. var camRight = this._rigCameras[1];
  32245. camLeft.beta = camRight.beta = this.beta;
  32246. camLeft.radius = camRight.radius = this.radius;
  32247. switch (this.cameraRigMode) {
  32248. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  32249. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  32250. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  32251. case BABYLON.Camera.RIG_MODE_VR:
  32252. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  32253. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  32254. break;
  32255. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  32256. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  32257. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  32258. break;
  32259. }
  32260. _super.prototype._updateRigCameras.call(this);
  32261. };
  32262. ArcRotateCamera.prototype.dispose = function () {
  32263. this.inputs.clear();
  32264. _super.prototype.dispose.call(this);
  32265. };
  32266. ArcRotateCamera.prototype.getClassName = function () {
  32267. return "ArcRotateCamera";
  32268. };
  32269. return ArcRotateCamera;
  32270. }(BABYLON.TargetCamera));
  32271. __decorate([
  32272. BABYLON.serialize()
  32273. ], ArcRotateCamera.prototype, "alpha", void 0);
  32274. __decorate([
  32275. BABYLON.serialize()
  32276. ], ArcRotateCamera.prototype, "beta", void 0);
  32277. __decorate([
  32278. BABYLON.serialize()
  32279. ], ArcRotateCamera.prototype, "radius", void 0);
  32280. __decorate([
  32281. BABYLON.serializeAsVector3("target")
  32282. ], ArcRotateCamera.prototype, "_target", void 0);
  32283. __decorate([
  32284. BABYLON.serialize()
  32285. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  32286. __decorate([
  32287. BABYLON.serialize()
  32288. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  32289. __decorate([
  32290. BABYLON.serialize()
  32291. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  32292. __decorate([
  32293. BABYLON.serialize()
  32294. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  32295. __decorate([
  32296. BABYLON.serialize()
  32297. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  32298. __decorate([
  32299. BABYLON.serialize()
  32300. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  32301. __decorate([
  32302. BABYLON.serialize()
  32303. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  32304. __decorate([
  32305. BABYLON.serialize()
  32306. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  32307. __decorate([
  32308. BABYLON.serialize()
  32309. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  32310. __decorate([
  32311. BABYLON.serialize()
  32312. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  32313. __decorate([
  32314. BABYLON.serialize()
  32315. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  32316. __decorate([
  32317. BABYLON.serialize()
  32318. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  32319. __decorate([
  32320. BABYLON.serialize()
  32321. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  32322. __decorate([
  32323. BABYLON.serialize()
  32324. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  32325. BABYLON.ArcRotateCamera = ArcRotateCamera;
  32326. })(BABYLON || (BABYLON = {}));
  32327. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  32328. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  32329. var BABYLON;
  32330. (function (BABYLON) {
  32331. var ArcRotateCameraInputsManager = (function (_super) {
  32332. __extends(ArcRotateCameraInputsManager, _super);
  32333. function ArcRotateCameraInputsManager(camera) {
  32334. return _super.call(this, camera) || this;
  32335. }
  32336. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  32337. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  32338. return this;
  32339. };
  32340. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  32341. this.add(new BABYLON.ArcRotateCameraPointersInput());
  32342. return this;
  32343. };
  32344. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  32345. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  32346. return this;
  32347. };
  32348. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  32349. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  32350. return this;
  32351. };
  32352. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  32353. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  32354. return this;
  32355. };
  32356. return ArcRotateCameraInputsManager;
  32357. }(BABYLON.CameraInputsManager));
  32358. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  32359. })(BABYLON || (BABYLON = {}));
  32360. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  32361. var BABYLON;
  32362. (function (BABYLON) {
  32363. var CubeTexture = (function (_super) {
  32364. __extends(CubeTexture, _super);
  32365. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format) {
  32366. if (onLoad === void 0) { onLoad = null; }
  32367. if (onError === void 0) { onError = null; }
  32368. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  32369. var _this = _super.call(this, scene) || this;
  32370. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  32371. _this.name = rootUrl;
  32372. _this.url = rootUrl;
  32373. _this._noMipmap = noMipmap;
  32374. _this.hasAlpha = false;
  32375. _this._format = format;
  32376. if (!rootUrl && !files) {
  32377. return _this;
  32378. }
  32379. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  32380. if (!files) {
  32381. if (!extensions) {
  32382. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  32383. }
  32384. files = [];
  32385. for (var index = 0; index < extensions.length; index++) {
  32386. files.push(rootUrl + extensions[index]);
  32387. }
  32388. _this._extensions = extensions;
  32389. }
  32390. _this._files = files;
  32391. if (!_this._texture) {
  32392. if (!scene.useDelayedTextureLoading) {
  32393. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format);
  32394. }
  32395. else {
  32396. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32397. }
  32398. }
  32399. else if (onLoad) {
  32400. if (_this._texture.isReady) {
  32401. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  32402. }
  32403. else {
  32404. _this._texture.onLoadedCallbacks.push(onLoad);
  32405. }
  32406. }
  32407. _this.isCube = true;
  32408. _this._textureMatrix = BABYLON.Matrix.Identity();
  32409. return _this;
  32410. }
  32411. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  32412. return new CubeTexture("", scene, null, noMipmap, files);
  32413. };
  32414. // Methods
  32415. CubeTexture.prototype.delayLoad = function () {
  32416. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32417. return;
  32418. }
  32419. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32420. this._texture = this._getFromCache(this.url, this._noMipmap);
  32421. if (!this._texture) {
  32422. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  32423. }
  32424. };
  32425. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  32426. return this._textureMatrix;
  32427. };
  32428. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  32429. var texture = BABYLON.SerializationHelper.Parse(function () {
  32430. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  32431. }, parsedTexture, scene);
  32432. // Animations
  32433. if (parsedTexture.animations) {
  32434. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  32435. var parsedAnimation = parsedTexture.animations[animationIndex];
  32436. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32437. }
  32438. }
  32439. return texture;
  32440. };
  32441. CubeTexture.prototype.clone = function () {
  32442. var _this = this;
  32443. return BABYLON.SerializationHelper.Clone(function () {
  32444. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  32445. }, this);
  32446. };
  32447. return CubeTexture;
  32448. }(BABYLON.BaseTexture));
  32449. BABYLON.CubeTexture = CubeTexture;
  32450. })(BABYLON || (BABYLON = {}));
  32451. //# sourceMappingURL=babylon.cubeTexture.js.map
  32452. var BABYLON;
  32453. (function (BABYLON) {
  32454. var RenderTargetTexture = (function (_super) {
  32455. __extends(RenderTargetTexture, _super);
  32456. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  32457. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  32458. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  32459. if (isCube === void 0) { isCube = false; }
  32460. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  32461. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  32462. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  32463. if (isMulti === void 0) { isMulti = false; }
  32464. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  32465. _this.isCube = isCube;
  32466. /**
  32467. * Use this list to define the list of mesh you want to render.
  32468. */
  32469. _this.renderList = new Array();
  32470. _this.renderParticles = true;
  32471. _this.renderSprites = false;
  32472. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  32473. // Events
  32474. /**
  32475. * An event triggered when the texture is unbind.
  32476. * @type {BABYLON.Observable}
  32477. */
  32478. _this.onAfterUnbindObservable = new BABYLON.Observable();
  32479. /**
  32480. * An event triggered before rendering the texture
  32481. * @type {BABYLON.Observable}
  32482. */
  32483. _this.onBeforeRenderObservable = new BABYLON.Observable();
  32484. /**
  32485. * An event triggered after rendering the texture
  32486. * @type {BABYLON.Observable}
  32487. */
  32488. _this.onAfterRenderObservable = new BABYLON.Observable();
  32489. /**
  32490. * An event triggered after the texture clear
  32491. * @type {BABYLON.Observable}
  32492. */
  32493. _this.onClearObservable = new BABYLON.Observable();
  32494. _this._currentRefreshId = -1;
  32495. _this._refreshRate = 1;
  32496. _this._samples = 1;
  32497. _this.name = name;
  32498. _this.isRenderTarget = true;
  32499. _this._size = size;
  32500. _this._generateMipMaps = generateMipMaps;
  32501. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  32502. // Rendering groups
  32503. _this._renderingManager = new BABYLON.RenderingManager(scene);
  32504. if (isMulti) {
  32505. return _this;
  32506. }
  32507. _this._renderTargetOptions = {
  32508. generateMipMaps: generateMipMaps,
  32509. type: type,
  32510. samplingMode: samplingMode,
  32511. generateDepthBuffer: generateDepthBuffer,
  32512. generateStencilBuffer: generateStencilBuffer
  32513. };
  32514. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  32515. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32516. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32517. }
  32518. if (isCube) {
  32519. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  32520. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  32521. _this._textureMatrix = BABYLON.Matrix.Identity();
  32522. }
  32523. else {
  32524. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  32525. }
  32526. return _this;
  32527. }
  32528. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  32529. get: function () {
  32530. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  32531. },
  32532. enumerable: true,
  32533. configurable: true
  32534. });
  32535. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  32536. get: function () {
  32537. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  32538. },
  32539. enumerable: true,
  32540. configurable: true
  32541. });
  32542. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  32543. get: function () {
  32544. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  32545. },
  32546. enumerable: true,
  32547. configurable: true
  32548. });
  32549. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  32550. set: function (callback) {
  32551. if (this._onAfterUnbindObserver) {
  32552. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  32553. }
  32554. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  32555. },
  32556. enumerable: true,
  32557. configurable: true
  32558. });
  32559. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  32560. set: function (callback) {
  32561. if (this._onBeforeRenderObserver) {
  32562. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  32563. }
  32564. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  32565. },
  32566. enumerable: true,
  32567. configurable: true
  32568. });
  32569. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  32570. set: function (callback) {
  32571. if (this._onAfterRenderObserver) {
  32572. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  32573. }
  32574. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  32575. },
  32576. enumerable: true,
  32577. configurable: true
  32578. });
  32579. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  32580. set: function (callback) {
  32581. if (this._onClearObserver) {
  32582. this.onClearObservable.remove(this._onClearObserver);
  32583. }
  32584. this._onClearObserver = this.onClearObservable.add(callback);
  32585. },
  32586. enumerable: true,
  32587. configurable: true
  32588. });
  32589. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  32590. get: function () {
  32591. return this._renderTargetOptions;
  32592. },
  32593. enumerable: true,
  32594. configurable: true
  32595. });
  32596. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  32597. get: function () {
  32598. return this._samples;
  32599. },
  32600. set: function (value) {
  32601. if (this._samples === value) {
  32602. return;
  32603. }
  32604. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  32605. },
  32606. enumerable: true,
  32607. configurable: true
  32608. });
  32609. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  32610. this._currentRefreshId = -1;
  32611. };
  32612. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  32613. get: function () {
  32614. return this._refreshRate;
  32615. },
  32616. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  32617. set: function (value) {
  32618. this._refreshRate = value;
  32619. this.resetRefreshCounter();
  32620. },
  32621. enumerable: true,
  32622. configurable: true
  32623. });
  32624. RenderTargetTexture.prototype._shouldRender = function () {
  32625. if (this._currentRefreshId === -1) {
  32626. this._currentRefreshId = 1;
  32627. return true;
  32628. }
  32629. if (this.refreshRate === this._currentRefreshId) {
  32630. this._currentRefreshId = 1;
  32631. return true;
  32632. }
  32633. this._currentRefreshId++;
  32634. return false;
  32635. };
  32636. RenderTargetTexture.prototype.isReady = function () {
  32637. if (!this.getScene().renderTargetsEnabled) {
  32638. return false;
  32639. }
  32640. return _super.prototype.isReady.call(this);
  32641. };
  32642. RenderTargetTexture.prototype.getRenderSize = function () {
  32643. return this._size;
  32644. };
  32645. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  32646. get: function () {
  32647. return true;
  32648. },
  32649. enumerable: true,
  32650. configurable: true
  32651. });
  32652. RenderTargetTexture.prototype.scale = function (ratio) {
  32653. var newSize = this._size * ratio;
  32654. this.resize(newSize);
  32655. };
  32656. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  32657. if (this.isCube) {
  32658. return this._textureMatrix;
  32659. }
  32660. return _super.prototype.getReflectionTextureMatrix.call(this);
  32661. };
  32662. RenderTargetTexture.prototype.resize = function (size) {
  32663. this.releaseInternalTexture();
  32664. if (this.isCube) {
  32665. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  32666. }
  32667. else {
  32668. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  32669. }
  32670. };
  32671. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  32672. var scene = this.getScene();
  32673. var engine = scene.getEngine();
  32674. if (this.useCameraPostProcesses !== undefined) {
  32675. useCameraPostProcess = this.useCameraPostProcesses;
  32676. }
  32677. if (this._waitingRenderList) {
  32678. this.renderList = [];
  32679. for (var index = 0; index < this._waitingRenderList.length; index++) {
  32680. var id = this._waitingRenderList[index];
  32681. this.renderList.push(scene.getMeshByID(id));
  32682. }
  32683. delete this._waitingRenderList;
  32684. }
  32685. // Is predicate defined?
  32686. if (this.renderListPredicate) {
  32687. this.renderList.splice(0); // Clear previous renderList
  32688. var sceneMeshes = this.getScene().meshes;
  32689. for (var index = 0; index < sceneMeshes.length; index++) {
  32690. var mesh = sceneMeshes[index];
  32691. if (this.renderListPredicate(mesh)) {
  32692. this.renderList.push(mesh);
  32693. }
  32694. }
  32695. }
  32696. if (this.renderList && this.renderList.length === 0) {
  32697. return;
  32698. }
  32699. // Set custom projection.
  32700. // Needs to be before binding to prevent changing the aspect ratio.
  32701. if (this.activeCamera) {
  32702. engine.setViewport(this.activeCamera.viewport);
  32703. if (this.activeCamera !== scene.activeCamera) {
  32704. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  32705. }
  32706. }
  32707. else {
  32708. engine.setViewport(scene.activeCamera.viewport);
  32709. }
  32710. // Prepare renderingManager
  32711. this._renderingManager.reset();
  32712. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  32713. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  32714. var sceneRenderId = scene.getRenderId();
  32715. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  32716. var mesh = currentRenderList[meshIndex];
  32717. if (mesh) {
  32718. if (!mesh.isReady()) {
  32719. // Reset _currentRefreshId
  32720. this.resetRefreshCounter();
  32721. continue;
  32722. }
  32723. mesh._preActivateForIntermediateRendering(sceneRenderId);
  32724. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  32725. mesh._activate(sceneRenderId);
  32726. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  32727. var subMesh = mesh.subMeshes[subIndex];
  32728. scene._activeIndices.addCount(subMesh.indexCount, false);
  32729. this._renderingManager.dispatch(subMesh);
  32730. }
  32731. }
  32732. }
  32733. }
  32734. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  32735. var particleSystem = scene.particleSystems[particleIndex];
  32736. if (!particleSystem.isStarted() || !particleSystem.emitter || !particleSystem.emitter.position || !particleSystem.emitter.isEnabled()) {
  32737. continue;
  32738. }
  32739. if (currentRenderList.indexOf(particleSystem.emitter) >= 0) {
  32740. this._renderingManager.dispatchParticles(particleSystem);
  32741. }
  32742. }
  32743. if (this.isCube) {
  32744. for (var face = 0; face < 6; face++) {
  32745. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  32746. scene.incrementRenderId();
  32747. scene.resetCachedMaterial();
  32748. }
  32749. }
  32750. else {
  32751. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  32752. }
  32753. this.onAfterUnbindObservable.notifyObservers(this);
  32754. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  32755. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  32756. }
  32757. engine.setViewport(scene.activeCamera.viewport);
  32758. scene.resetCachedMaterial();
  32759. };
  32760. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  32761. var _this = this;
  32762. var scene = this.getScene();
  32763. var engine = scene.getEngine();
  32764. // Bind
  32765. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  32766. if (this.isCube) {
  32767. engine.bindFramebuffer(this._texture, faceIndex);
  32768. }
  32769. else {
  32770. engine.bindFramebuffer(this._texture);
  32771. }
  32772. }
  32773. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  32774. // Clear
  32775. if (this.onClearObservable.hasObservers()) {
  32776. this.onClearObservable.notifyObservers(engine);
  32777. }
  32778. else {
  32779. engine.clear(scene.clearColor, true, true, true);
  32780. }
  32781. if (!this._doNotChangeAspectRatio) {
  32782. scene.updateTransformMatrix(true);
  32783. }
  32784. // Render
  32785. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  32786. if (useCameraPostProcess) {
  32787. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  32788. }
  32789. if (!this._doNotChangeAspectRatio) {
  32790. scene.updateTransformMatrix(true);
  32791. }
  32792. // Dump ?
  32793. if (dumpForDebug) {
  32794. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  32795. }
  32796. // Unbind
  32797. if (!this.isCube || faceIndex === 5) {
  32798. if (this.isCube) {
  32799. if (faceIndex === 5) {
  32800. engine.generateMipMapsForCubemap(this._texture);
  32801. }
  32802. }
  32803. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  32804. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  32805. });
  32806. }
  32807. else {
  32808. this.onAfterRenderObservable.notifyObservers(faceIndex);
  32809. }
  32810. };
  32811. /**
  32812. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  32813. * This allowed control for front to back rendering or reversly depending of the special needs.
  32814. *
  32815. * @param renderingGroupId The rendering group id corresponding to its index
  32816. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  32817. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  32818. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  32819. */
  32820. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  32821. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  32822. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  32823. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  32824. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  32825. };
  32826. /**
  32827. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  32828. *
  32829. * @param renderingGroupId The rendering group id corresponding to its index
  32830. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  32831. */
  32832. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  32833. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  32834. };
  32835. RenderTargetTexture.prototype.clone = function () {
  32836. var textureSize = this.getSize();
  32837. 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);
  32838. // Base texture
  32839. newTexture.hasAlpha = this.hasAlpha;
  32840. newTexture.level = this.level;
  32841. // RenderTarget Texture
  32842. newTexture.coordinatesMode = this.coordinatesMode;
  32843. newTexture.renderList = this.renderList.slice(0);
  32844. return newTexture;
  32845. };
  32846. RenderTargetTexture.prototype.serialize = function () {
  32847. if (!this.name) {
  32848. return null;
  32849. }
  32850. var serializationObject = _super.prototype.serialize.call(this);
  32851. serializationObject.renderTargetSize = this.getRenderSize();
  32852. serializationObject.renderList = [];
  32853. for (var index = 0; index < this.renderList.length; index++) {
  32854. serializationObject.renderList.push(this.renderList[index].id);
  32855. }
  32856. return serializationObject;
  32857. };
  32858. RenderTargetTexture.prototype.dispose = function () {
  32859. _super.prototype.dispose.call(this);
  32860. };
  32861. return RenderTargetTexture;
  32862. }(BABYLON.Texture));
  32863. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  32864. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  32865. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  32866. BABYLON.RenderTargetTexture = RenderTargetTexture;
  32867. })(BABYLON || (BABYLON = {}));
  32868. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  32869. var BABYLON;
  32870. (function (BABYLON) {
  32871. ;
  32872. var MultiRenderTarget = (function (_super) {
  32873. __extends(MultiRenderTarget, _super);
  32874. function MultiRenderTarget(name, size, count, scene, options) {
  32875. var _this = this;
  32876. options = options || {};
  32877. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  32878. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  32879. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  32880. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  32881. if (!_this.isSupported) {
  32882. _this.dispose();
  32883. return;
  32884. }
  32885. var types = [];
  32886. var samplingModes = [];
  32887. for (var i = 0; i < count; i++) {
  32888. if (options.types && options.types[i]) {
  32889. types.push(options.types[i]);
  32890. }
  32891. else {
  32892. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  32893. }
  32894. if (options.samplingModes && options.samplingModes[i]) {
  32895. samplingModes.push(options.samplingModes[i]);
  32896. }
  32897. else {
  32898. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32899. }
  32900. }
  32901. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  32902. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  32903. _this._count = count;
  32904. _this._size = size;
  32905. _this._multiRenderTargetOptions = {
  32906. samplingModes: samplingModes,
  32907. generateMipMaps: generateMipMaps,
  32908. generateDepthBuffer: generateDepthBuffer,
  32909. generateStencilBuffer: generateStencilBuffer,
  32910. generateDepthTexture: generateDepthTexture,
  32911. types: types,
  32912. textureCount: count
  32913. };
  32914. _this._webGLTextures = scene.getEngine().createMultipleRenderTarget(size, _this._multiRenderTargetOptions);
  32915. _this._createInternalTextures();
  32916. return _this;
  32917. }
  32918. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  32919. get: function () {
  32920. var engine = this.getScene().getEngine();
  32921. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  32922. },
  32923. enumerable: true,
  32924. configurable: true
  32925. });
  32926. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  32927. get: function () {
  32928. return this._textures;
  32929. },
  32930. enumerable: true,
  32931. configurable: true
  32932. });
  32933. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  32934. get: function () {
  32935. return this._textures[this._textures.length - 1];
  32936. },
  32937. enumerable: true,
  32938. configurable: true
  32939. });
  32940. MultiRenderTarget.prototype._createInternalTextures = function () {
  32941. this._textures = [];
  32942. for (var i = 0; i < this._webGLTextures.length; i++) {
  32943. var texture = new BABYLON.Texture(null, this.getScene());
  32944. texture._texture = this._webGLTextures[i];
  32945. this._textures.push(texture);
  32946. }
  32947. // Keeps references to frame buffer and stencil/depth buffer
  32948. this._texture = this._webGLTextures[0];
  32949. };
  32950. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  32951. get: function () {
  32952. return this._samples;
  32953. },
  32954. set: function (value) {
  32955. if (this._samples === value) {
  32956. return;
  32957. }
  32958. for (var i = 0; i < this._webGLTextures.length; i++) {
  32959. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._webGLTextures[i], value);
  32960. }
  32961. },
  32962. enumerable: true,
  32963. configurable: true
  32964. });
  32965. MultiRenderTarget.prototype.resize = function (size) {
  32966. this.releaseInternalTextures();
  32967. this._webGLTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  32968. this._createInternalTextures();
  32969. };
  32970. MultiRenderTarget.prototype.dispose = function () {
  32971. this.releaseInternalTextures();
  32972. _super.prototype.dispose.call(this);
  32973. };
  32974. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  32975. if (!this._webGLTextures) {
  32976. return;
  32977. }
  32978. for (var i = this._webGLTextures.length - 1; i >= 0; i--) {
  32979. if (this._webGLTextures[i] !== undefined) {
  32980. this.getScene().getEngine().releaseInternalTexture(this._webGLTextures[i]);
  32981. this._webGLTextures.splice(i, 1);
  32982. }
  32983. }
  32984. };
  32985. return MultiRenderTarget;
  32986. }(BABYLON.RenderTargetTexture));
  32987. BABYLON.MultiRenderTarget = MultiRenderTarget;
  32988. })(BABYLON || (BABYLON = {}));
  32989. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  32990. /// <reference path="babylon.renderTargetTexture.ts" />
  32991. var BABYLON;
  32992. (function (BABYLON) {
  32993. var MirrorTexture = (function (_super) {
  32994. __extends(MirrorTexture, _super);
  32995. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  32996. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  32997. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  32998. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  32999. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  33000. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  33001. _this._transformMatrix = BABYLON.Matrix.Zero();
  33002. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  33003. _this.onBeforeRenderObservable.add(function () {
  33004. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  33005. _this._savedViewMatrix = scene.getViewMatrix();
  33006. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  33007. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  33008. scene.clipPlane = _this.mirrorPlane;
  33009. scene.getEngine().cullBackFaces = false;
  33010. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  33011. });
  33012. _this.onAfterRenderObservable.add(function () {
  33013. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  33014. scene.getEngine().cullBackFaces = true;
  33015. scene._mirroredCameraPosition = null;
  33016. delete scene.clipPlane;
  33017. });
  33018. return _this;
  33019. }
  33020. MirrorTexture.prototype.clone = function () {
  33021. var textureSize = this.getSize();
  33022. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  33023. // Base texture
  33024. newTexture.hasAlpha = this.hasAlpha;
  33025. newTexture.level = this.level;
  33026. // Mirror Texture
  33027. newTexture.mirrorPlane = this.mirrorPlane.clone();
  33028. newTexture.renderList = this.renderList.slice(0);
  33029. return newTexture;
  33030. };
  33031. MirrorTexture.prototype.serialize = function () {
  33032. if (!this.name) {
  33033. return null;
  33034. }
  33035. var serializationObject = _super.prototype.serialize.call(this);
  33036. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  33037. return serializationObject;
  33038. };
  33039. return MirrorTexture;
  33040. }(BABYLON.RenderTargetTexture));
  33041. BABYLON.MirrorTexture = MirrorTexture;
  33042. })(BABYLON || (BABYLON = {}));
  33043. //# sourceMappingURL=babylon.mirrorTexture.js.map
  33044. /// <reference path="babylon.renderTargetTexture.ts" />
  33045. var BABYLON;
  33046. (function (BABYLON) {
  33047. /**
  33048. * Creates a refraction texture used by refraction channel of the standard material.
  33049. * @param name the texture name
  33050. * @param size size of the underlying texture
  33051. * @param scene root scene
  33052. */
  33053. var RefractionTexture = (function (_super) {
  33054. __extends(RefractionTexture, _super);
  33055. function RefractionTexture(name, size, scene, generateMipMaps) {
  33056. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  33057. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  33058. _this.depth = 2.0;
  33059. _this.onBeforeRenderObservable.add(function () {
  33060. scene.clipPlane = _this.refractionPlane;
  33061. });
  33062. _this.onAfterRenderObservable.add(function () {
  33063. delete scene.clipPlane;
  33064. });
  33065. return _this;
  33066. }
  33067. RefractionTexture.prototype.clone = function () {
  33068. var textureSize = this.getSize();
  33069. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  33070. // Base texture
  33071. newTexture.hasAlpha = this.hasAlpha;
  33072. newTexture.level = this.level;
  33073. // Refraction Texture
  33074. newTexture.refractionPlane = this.refractionPlane.clone();
  33075. newTexture.renderList = this.renderList.slice(0);
  33076. newTexture.depth = this.depth;
  33077. return newTexture;
  33078. };
  33079. RefractionTexture.prototype.serialize = function () {
  33080. if (!this.name) {
  33081. return null;
  33082. }
  33083. var serializationObject = _super.prototype.serialize.call(this);
  33084. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  33085. serializationObject.depth = this.depth;
  33086. return serializationObject;
  33087. };
  33088. return RefractionTexture;
  33089. }(BABYLON.RenderTargetTexture));
  33090. BABYLON.RefractionTexture = RefractionTexture;
  33091. })(BABYLON || (BABYLON = {}));
  33092. //# sourceMappingURL=babylon.refractionTexture.js.map
  33093. /// <reference path="babylon.texture.ts" />
  33094. var BABYLON;
  33095. (function (BABYLON) {
  33096. var DynamicTexture = (function (_super) {
  33097. __extends(DynamicTexture, _super);
  33098. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  33099. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33100. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  33101. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  33102. _this.name = name;
  33103. var engine = _this.getScene().getEngine();
  33104. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33105. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33106. _this._generateMipMaps = generateMipMaps;
  33107. if (options.getContext) {
  33108. _this._canvas = options;
  33109. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  33110. }
  33111. else {
  33112. _this._canvas = document.createElement("canvas");
  33113. if (options.width) {
  33114. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  33115. }
  33116. else {
  33117. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  33118. }
  33119. }
  33120. var textureSize = _this.getSize();
  33121. _this._canvas.width = textureSize.width;
  33122. _this._canvas.height = textureSize.height;
  33123. _this._context = _this._canvas.getContext("2d");
  33124. return _this;
  33125. }
  33126. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  33127. get: function () {
  33128. return true;
  33129. },
  33130. enumerable: true,
  33131. configurable: true
  33132. });
  33133. DynamicTexture.prototype._recreate = function (textureSize) {
  33134. this._canvas.width = textureSize.width;
  33135. this._canvas.height = textureSize.height;
  33136. this.releaseInternalTexture();
  33137. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  33138. };
  33139. DynamicTexture.prototype.scale = function (ratio) {
  33140. var textureSize = this.getSize();
  33141. textureSize.width *= ratio;
  33142. textureSize.height *= ratio;
  33143. this._recreate(textureSize);
  33144. };
  33145. DynamicTexture.prototype.scaleTo = function (width, height) {
  33146. var textureSize = this.getSize();
  33147. textureSize.width = width;
  33148. textureSize.height = height;
  33149. this._recreate(textureSize);
  33150. };
  33151. DynamicTexture.prototype.getContext = function () {
  33152. return this._context;
  33153. };
  33154. DynamicTexture.prototype.clear = function () {
  33155. var size = this.getSize();
  33156. this._context.fillRect(0, 0, size.width, size.height);
  33157. };
  33158. DynamicTexture.prototype.update = function (invertY) {
  33159. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  33160. };
  33161. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  33162. if (update === void 0) { update = true; }
  33163. var size = this.getSize();
  33164. if (clearColor) {
  33165. this._context.fillStyle = clearColor;
  33166. this._context.fillRect(0, 0, size.width, size.height);
  33167. }
  33168. this._context.font = font;
  33169. if (x === null || x === undefined) {
  33170. var textSize = this._context.measureText(text);
  33171. x = (size.width - textSize.width) / 2;
  33172. }
  33173. if (y === null || y === undefined) {
  33174. var fontSize = parseInt((font.replace(/\D/g, '')));
  33175. ;
  33176. y = (size.height / 2) + (fontSize / 3.65);
  33177. }
  33178. this._context.fillStyle = color;
  33179. this._context.fillText(text, x, y);
  33180. if (update) {
  33181. this.update(invertY);
  33182. }
  33183. };
  33184. DynamicTexture.prototype.clone = function () {
  33185. var textureSize = this.getSize();
  33186. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  33187. // Base texture
  33188. newTexture.hasAlpha = this.hasAlpha;
  33189. newTexture.level = this.level;
  33190. // Dynamic Texture
  33191. newTexture.wrapU = this.wrapU;
  33192. newTexture.wrapV = this.wrapV;
  33193. return newTexture;
  33194. };
  33195. return DynamicTexture;
  33196. }(BABYLON.Texture));
  33197. BABYLON.DynamicTexture = DynamicTexture;
  33198. })(BABYLON || (BABYLON = {}));
  33199. //# sourceMappingURL=babylon.dynamicTexture.js.map
  33200. var BABYLON;
  33201. (function (BABYLON) {
  33202. var VideoTexture = (function (_super) {
  33203. __extends(VideoTexture, _super);
  33204. /**
  33205. * Creates a video texture.
  33206. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  33207. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  33208. * @param {BABYLON.Scene} scene is obviously the current scene.
  33209. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  33210. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  33211. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  33212. */
  33213. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  33214. if (generateMipMaps === void 0) { generateMipMaps = false; }
  33215. if (invertY === void 0) { invertY = false; }
  33216. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33217. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  33218. _this._autoLaunch = true;
  33219. var urls;
  33220. _this.name = name;
  33221. if (urlsOrVideo instanceof HTMLVideoElement) {
  33222. _this.video = urlsOrVideo;
  33223. }
  33224. else {
  33225. urls = urlsOrVideo;
  33226. _this.video = document.createElement("video");
  33227. _this.video.autoplay = false;
  33228. _this.video.loop = true;
  33229. }
  33230. _this._generateMipMaps = generateMipMaps;
  33231. _this._samplingMode = samplingMode;
  33232. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  33233. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  33234. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  33235. }
  33236. else {
  33237. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33238. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33239. _this._generateMipMaps = false;
  33240. }
  33241. if (urls) {
  33242. _this.video.addEventListener("canplay", function () {
  33243. _this._createTexture();
  33244. });
  33245. urls.forEach(function (url) {
  33246. var source = document.createElement("source");
  33247. source.src = url;
  33248. _this.video.appendChild(source);
  33249. });
  33250. }
  33251. else {
  33252. _this._createTexture();
  33253. }
  33254. _this._lastUpdate = BABYLON.Tools.Now;
  33255. return _this;
  33256. }
  33257. VideoTexture.prototype.__setTextureReady = function () {
  33258. this._texture.isReady = true;
  33259. };
  33260. VideoTexture.prototype._createTexture = function () {
  33261. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  33262. if (this._autoLaunch) {
  33263. this._autoLaunch = false;
  33264. this.video.play();
  33265. }
  33266. this._setTextureReady = this.__setTextureReady.bind(this);
  33267. this.video.addEventListener("playing", this._setTextureReady);
  33268. };
  33269. VideoTexture.prototype.update = function () {
  33270. var now = BABYLON.Tools.Now;
  33271. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  33272. return false;
  33273. }
  33274. this._lastUpdate = now;
  33275. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  33276. return true;
  33277. };
  33278. VideoTexture.prototype.dispose = function () {
  33279. _super.prototype.dispose.call(this);
  33280. this.video.removeEventListener("playing", this._setTextureReady);
  33281. };
  33282. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  33283. var video = document.createElement("video");
  33284. var constraintsDeviceId;
  33285. if (constraints && constraints.deviceId) {
  33286. constraintsDeviceId = {
  33287. exact: constraints.deviceId
  33288. };
  33289. }
  33290. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  33291. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  33292. if (navigator.getUserMedia) {
  33293. navigator.getUserMedia({
  33294. video: {
  33295. deviceId: constraintsDeviceId,
  33296. width: {
  33297. min: (constraints && constraints.minWidth) || 256,
  33298. max: (constraints && constraints.maxWidth) || 640
  33299. },
  33300. height: {
  33301. min: (constraints && constraints.minHeight) || 256,
  33302. max: (constraints && constraints.maxHeight) || 480
  33303. }
  33304. }
  33305. }, function (stream) {
  33306. if (video.mozSrcObject !== undefined) {
  33307. video.mozSrcObject = stream;
  33308. }
  33309. else {
  33310. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  33311. }
  33312. video.play();
  33313. if (onReady) {
  33314. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  33315. }
  33316. }, function (e) {
  33317. BABYLON.Tools.Error(e.name);
  33318. });
  33319. }
  33320. };
  33321. return VideoTexture;
  33322. }(BABYLON.Texture));
  33323. BABYLON.VideoTexture = VideoTexture;
  33324. })(BABYLON || (BABYLON = {}));
  33325. //# sourceMappingURL=babylon.videoTexture.js.map
  33326. var BABYLON;
  33327. (function (BABYLON) {
  33328. var RawTexture = (function (_super) {
  33329. __extends(RawTexture, _super);
  33330. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  33331. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33332. if (invertY === void 0) { invertY = false; }
  33333. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33334. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  33335. _this.format = format;
  33336. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  33337. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33338. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33339. return _this;
  33340. }
  33341. RawTexture.prototype.update = function (data) {
  33342. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  33343. };
  33344. // Statics
  33345. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33346. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33347. if (invertY === void 0) { invertY = false; }
  33348. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33349. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  33350. };
  33351. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33352. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33353. if (invertY === void 0) { invertY = false; }
  33354. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33355. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  33356. };
  33357. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33358. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33359. if (invertY === void 0) { invertY = false; }
  33360. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33361. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  33362. };
  33363. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33364. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33365. if (invertY === void 0) { invertY = false; }
  33366. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33367. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  33368. };
  33369. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  33370. if (generateMipMaps === void 0) { generateMipMaps = true; }
  33371. if (invertY === void 0) { invertY = false; }
  33372. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  33373. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  33374. };
  33375. return RawTexture;
  33376. }(BABYLON.Texture));
  33377. BABYLON.RawTexture = RawTexture;
  33378. })(BABYLON || (BABYLON = {}));
  33379. //# sourceMappingURL=babylon.rawTexture.js.map
  33380. var BABYLON;
  33381. (function (BABYLON) {
  33382. var Internals;
  33383. (function (Internals) {
  33384. /*
  33385. * Based on jsTGALoader - Javascript loader for TGA file
  33386. * By Vincent Thibault
  33387. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  33388. */
  33389. var TGATools = (function () {
  33390. function TGATools() {
  33391. }
  33392. TGATools.GetTGAHeader = function (data) {
  33393. var offset = 0;
  33394. var header = {
  33395. id_length: data[offset++],
  33396. colormap_type: data[offset++],
  33397. image_type: data[offset++],
  33398. colormap_index: data[offset++] | data[offset++] << 8,
  33399. colormap_length: data[offset++] | data[offset++] << 8,
  33400. colormap_size: data[offset++],
  33401. origin: [
  33402. data[offset++] | data[offset++] << 8,
  33403. data[offset++] | data[offset++] << 8
  33404. ],
  33405. width: data[offset++] | data[offset++] << 8,
  33406. height: data[offset++] | data[offset++] << 8,
  33407. pixel_size: data[offset++],
  33408. flags: data[offset++]
  33409. };
  33410. return header;
  33411. };
  33412. TGATools.UploadContent = function (gl, data) {
  33413. // Not enough data to contain header ?
  33414. if (data.length < 19) {
  33415. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  33416. return;
  33417. }
  33418. // Read Header
  33419. var offset = 18;
  33420. var header = TGATools.GetTGAHeader(data);
  33421. // Assume it's a valid Targa file.
  33422. if (header.id_length + offset > data.length) {
  33423. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  33424. return;
  33425. }
  33426. // Skip not needed data
  33427. offset += header.id_length;
  33428. var use_rle = false;
  33429. var use_pal = false;
  33430. var use_rgb = false;
  33431. var use_grey = false;
  33432. // Get some informations.
  33433. switch (header.image_type) {
  33434. case TGATools._TYPE_RLE_INDEXED:
  33435. use_rle = true;
  33436. case TGATools._TYPE_INDEXED:
  33437. use_pal = true;
  33438. break;
  33439. case TGATools._TYPE_RLE_RGB:
  33440. use_rle = true;
  33441. case TGATools._TYPE_RGB:
  33442. use_rgb = true;
  33443. break;
  33444. case TGATools._TYPE_RLE_GREY:
  33445. use_rle = true;
  33446. case TGATools._TYPE_GREY:
  33447. use_grey = true;
  33448. break;
  33449. }
  33450. var pixel_data;
  33451. var numAlphaBits = header.flags & 0xf;
  33452. var pixel_size = header.pixel_size >> 3;
  33453. var pixel_total = header.width * header.height * pixel_size;
  33454. // Read palettes
  33455. var palettes;
  33456. if (use_pal) {
  33457. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  33458. }
  33459. // Read LRE
  33460. if (use_rle) {
  33461. pixel_data = new Uint8Array(pixel_total);
  33462. var c, count, i;
  33463. var localOffset = 0;
  33464. var pixels = new Uint8Array(pixel_size);
  33465. while (offset < pixel_total && localOffset < pixel_total) {
  33466. c = data[offset++];
  33467. count = (c & 0x7f) + 1;
  33468. // RLE pixels
  33469. if (c & 0x80) {
  33470. // Bind pixel tmp array
  33471. for (i = 0; i < pixel_size; ++i) {
  33472. pixels[i] = data[offset++];
  33473. }
  33474. // Copy pixel array
  33475. for (i = 0; i < count; ++i) {
  33476. pixel_data.set(pixels, localOffset + i * pixel_size);
  33477. }
  33478. localOffset += pixel_size * count;
  33479. }
  33480. else {
  33481. count *= pixel_size;
  33482. for (i = 0; i < count; ++i) {
  33483. pixel_data[localOffset + i] = data[offset++];
  33484. }
  33485. localOffset += count;
  33486. }
  33487. }
  33488. }
  33489. else {
  33490. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  33491. }
  33492. // Load to texture
  33493. var x_start, y_start, x_step, y_step, y_end, x_end;
  33494. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  33495. default:
  33496. case TGATools._ORIGIN_UL:
  33497. x_start = 0;
  33498. x_step = 1;
  33499. x_end = header.width;
  33500. y_start = 0;
  33501. y_step = 1;
  33502. y_end = header.height;
  33503. break;
  33504. case TGATools._ORIGIN_BL:
  33505. x_start = 0;
  33506. x_step = 1;
  33507. x_end = header.width;
  33508. y_start = header.height - 1;
  33509. y_step = -1;
  33510. y_end = -1;
  33511. break;
  33512. case TGATools._ORIGIN_UR:
  33513. x_start = header.width - 1;
  33514. x_step = -1;
  33515. x_end = -1;
  33516. y_start = 0;
  33517. y_step = 1;
  33518. y_end = header.height;
  33519. break;
  33520. case TGATools._ORIGIN_BR:
  33521. x_start = header.width - 1;
  33522. x_step = -1;
  33523. x_end = -1;
  33524. y_start = header.height - 1;
  33525. y_step = -1;
  33526. y_end = -1;
  33527. break;
  33528. }
  33529. // Load the specify method
  33530. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  33531. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  33532. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  33533. };
  33534. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  33535. var image = pixel_data, colormap = palettes;
  33536. var width = header.width, height = header.height;
  33537. var color, i = 0, x, y;
  33538. var imageData = new Uint8Array(width * height * 4);
  33539. for (y = y_start; y !== y_end; y += y_step) {
  33540. for (x = x_start; x !== x_end; x += x_step, i++) {
  33541. color = image[i];
  33542. imageData[(x + width * y) * 4 + 3] = 255;
  33543. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  33544. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  33545. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  33546. }
  33547. }
  33548. return imageData;
  33549. };
  33550. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  33551. var image = pixel_data;
  33552. var width = header.width, height = header.height;
  33553. var color, i = 0, x, y;
  33554. var imageData = new Uint8Array(width * height * 4);
  33555. for (y = y_start; y !== y_end; y += y_step) {
  33556. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  33557. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  33558. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  33559. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  33560. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  33561. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  33562. }
  33563. }
  33564. return imageData;
  33565. };
  33566. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  33567. var image = pixel_data;
  33568. var width = header.width, height = header.height;
  33569. var i = 0, x, y;
  33570. var imageData = new Uint8Array(width * height * 4);
  33571. for (y = y_start; y !== y_end; y += y_step) {
  33572. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  33573. imageData[(x + width * y) * 4 + 3] = 255;
  33574. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  33575. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  33576. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  33577. }
  33578. }
  33579. return imageData;
  33580. };
  33581. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  33582. var image = pixel_data;
  33583. var width = header.width, height = header.height;
  33584. var i = 0, x, y;
  33585. var imageData = new Uint8Array(width * height * 4);
  33586. for (y = y_start; y !== y_end; y += y_step) {
  33587. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  33588. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  33589. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  33590. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  33591. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  33592. }
  33593. }
  33594. return imageData;
  33595. };
  33596. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  33597. var image = pixel_data;
  33598. var width = header.width, height = header.height;
  33599. var color, i = 0, x, y;
  33600. var imageData = new Uint8Array(width * height * 4);
  33601. for (y = y_start; y !== y_end; y += y_step) {
  33602. for (x = x_start; x !== x_end; x += x_step, i++) {
  33603. color = image[i];
  33604. imageData[(x + width * y) * 4 + 0] = color;
  33605. imageData[(x + width * y) * 4 + 1] = color;
  33606. imageData[(x + width * y) * 4 + 2] = color;
  33607. imageData[(x + width * y) * 4 + 3] = 255;
  33608. }
  33609. }
  33610. return imageData;
  33611. };
  33612. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  33613. var image = pixel_data;
  33614. var width = header.width, height = header.height;
  33615. var i = 0, x, y;
  33616. var imageData = new Uint8Array(width * height * 4);
  33617. for (y = y_start; y !== y_end; y += y_step) {
  33618. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  33619. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  33620. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  33621. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  33622. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  33623. }
  33624. }
  33625. return imageData;
  33626. };
  33627. return TGATools;
  33628. }());
  33629. TGATools._TYPE_NO_DATA = 0;
  33630. TGATools._TYPE_INDEXED = 1;
  33631. TGATools._TYPE_RGB = 2;
  33632. TGATools._TYPE_GREY = 3;
  33633. TGATools._TYPE_RLE_INDEXED = 9;
  33634. TGATools._TYPE_RLE_RGB = 10;
  33635. TGATools._TYPE_RLE_GREY = 11;
  33636. TGATools._ORIGIN_MASK = 0x30;
  33637. TGATools._ORIGIN_SHIFT = 0x04;
  33638. TGATools._ORIGIN_BL = 0x00;
  33639. TGATools._ORIGIN_BR = 0x01;
  33640. TGATools._ORIGIN_UL = 0x02;
  33641. TGATools._ORIGIN_UR = 0x03;
  33642. Internals.TGATools = TGATools;
  33643. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  33644. })(BABYLON || (BABYLON = {}));
  33645. //# sourceMappingURL=babylon.tga.js.map
  33646. var BABYLON;
  33647. (function (BABYLON) {
  33648. var Internals;
  33649. (function (Internals) {
  33650. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  33651. // All values and structures referenced from:
  33652. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  33653. var DDS_MAGIC = 0x20534444;
  33654. 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;
  33655. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  33656. 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;
  33657. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  33658. function FourCCToInt32(value) {
  33659. return value.charCodeAt(0) +
  33660. (value.charCodeAt(1) << 8) +
  33661. (value.charCodeAt(2) << 16) +
  33662. (value.charCodeAt(3) << 24);
  33663. }
  33664. function Int32ToFourCC(value) {
  33665. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  33666. }
  33667. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  33668. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  33669. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  33670. var headerLengthInt = 31; // The header length in 32 bit ints
  33671. // Offsets into the header array
  33672. var off_magic = 0;
  33673. var off_size = 1;
  33674. var off_flags = 2;
  33675. var off_height = 3;
  33676. var off_width = 4;
  33677. var off_mipmapCount = 7;
  33678. var off_pfFlags = 20;
  33679. var off_pfFourCC = 21;
  33680. var off_RGBbpp = 22;
  33681. var off_RMask = 23;
  33682. var off_GMask = 24;
  33683. var off_BMask = 25;
  33684. var off_AMask = 26;
  33685. var off_caps1 = 27;
  33686. var off_caps2 = 28;
  33687. ;
  33688. var DDSTools = (function () {
  33689. function DDSTools() {
  33690. }
  33691. DDSTools.GetDDSInfo = function (arrayBuffer) {
  33692. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  33693. var mipmapCount = 1;
  33694. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  33695. mipmapCount = Math.max(1, header[off_mipmapCount]);
  33696. }
  33697. return {
  33698. width: header[off_width],
  33699. height: header[off_height],
  33700. mipmapCount: mipmapCount,
  33701. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  33702. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  33703. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  33704. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  33705. };
  33706. };
  33707. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  33708. var byteArray = new Uint8Array(dataLength);
  33709. var srcData = new Uint8Array(arrayBuffer);
  33710. var index = 0;
  33711. for (var y = height - 1; y >= 0; y--) {
  33712. for (var x = 0; x < width; x++) {
  33713. var srcPos = dataOffset + (x + y * width) * 4;
  33714. byteArray[index + 2] = srcData[srcPos];
  33715. byteArray[index + 1] = srcData[srcPos + 1];
  33716. byteArray[index] = srcData[srcPos + 2];
  33717. byteArray[index + 3] = srcData[srcPos + 3];
  33718. index += 4;
  33719. }
  33720. }
  33721. return byteArray;
  33722. };
  33723. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  33724. var byteArray = new Uint8Array(dataLength);
  33725. var srcData = new Uint8Array(arrayBuffer);
  33726. var index = 0;
  33727. for (var y = height - 1; y >= 0; y--) {
  33728. for (var x = 0; x < width; x++) {
  33729. var srcPos = dataOffset + (x + y * width) * 3;
  33730. byteArray[index + 2] = srcData[srcPos];
  33731. byteArray[index + 1] = srcData[srcPos + 1];
  33732. byteArray[index] = srcData[srcPos + 2];
  33733. index += 3;
  33734. }
  33735. }
  33736. return byteArray;
  33737. };
  33738. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  33739. var byteArray = new Uint8Array(dataLength);
  33740. var srcData = new Uint8Array(arrayBuffer);
  33741. var index = 0;
  33742. for (var y = height - 1; y >= 0; y--) {
  33743. for (var x = 0; x < width; x++) {
  33744. var srcPos = dataOffset + (x + y * width);
  33745. byteArray[index] = srcData[srcPos];
  33746. index++;
  33747. }
  33748. }
  33749. return byteArray;
  33750. };
  33751. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  33752. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  33753. if (header[off_magic] != DDS_MAGIC) {
  33754. BABYLON.Tools.Error("Invalid magic number in DDS header");
  33755. return;
  33756. }
  33757. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  33758. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  33759. return;
  33760. }
  33761. if (info.isFourCC) {
  33762. fourCC = header[off_pfFourCC];
  33763. switch (fourCC) {
  33764. case FOURCC_DXT1:
  33765. blockBytes = 8;
  33766. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  33767. break;
  33768. case FOURCC_DXT3:
  33769. blockBytes = 16;
  33770. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  33771. break;
  33772. case FOURCC_DXT5:
  33773. blockBytes = 16;
  33774. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  33775. break;
  33776. default:
  33777. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  33778. return;
  33779. }
  33780. }
  33781. mipmapCount = 1;
  33782. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  33783. mipmapCount = Math.max(1, header[off_mipmapCount]);
  33784. }
  33785. var bpp = header[off_RGBbpp];
  33786. for (var face = 0; face < faces; face++) {
  33787. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  33788. width = header[off_width];
  33789. height = header[off_height];
  33790. dataOffset = header[off_size] + 4;
  33791. for (i = 0; i < mipmapCount; ++i) {
  33792. if (info.isRGB) {
  33793. if (bpp === 24) {
  33794. dataLength = width * height * 3;
  33795. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  33796. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  33797. }
  33798. else {
  33799. dataLength = width * height * 4;
  33800. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  33801. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  33802. }
  33803. }
  33804. else if (info.isLuminance) {
  33805. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  33806. var unpaddedRowSize = width;
  33807. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  33808. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  33809. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  33810. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  33811. }
  33812. else {
  33813. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  33814. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  33815. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  33816. }
  33817. dataOffset += dataLength;
  33818. width *= 0.5;
  33819. height *= 0.5;
  33820. width = Math.max(1.0, width);
  33821. height = Math.max(1.0, height);
  33822. }
  33823. }
  33824. };
  33825. return DDSTools;
  33826. }());
  33827. Internals.DDSTools = DDSTools;
  33828. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  33829. })(BABYLON || (BABYLON = {}));
  33830. //# sourceMappingURL=babylon.dds.js.map
  33831. var BABYLON;
  33832. (function (BABYLON) {
  33833. var Internals;
  33834. (function (Internals) {
  33835. /**
  33836. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  33837. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  33838. */
  33839. var KhronosTextureContainer = (function () {
  33840. /**
  33841. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  33842. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  33843. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  33844. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  33845. */
  33846. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  33847. this.arrayBuffer = arrayBuffer;
  33848. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  33849. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  33850. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  33851. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  33852. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  33853. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  33854. BABYLON.Tools.Error("texture missing KTX identifier");
  33855. return;
  33856. }
  33857. // load the reset of the header in native 32 bit int
  33858. var header = new Int32Array(this.arrayBuffer, 12, 13);
  33859. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  33860. var oppositeEndianess = header[0] === 0x01020304;
  33861. // read all the header elements in order they exist in the file, without modification (sans endainness)
  33862. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  33863. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  33864. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  33865. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  33866. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  33867. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  33868. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  33869. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  33870. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  33871. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  33872. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  33873. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  33874. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  33875. if (this.glType !== 0) {
  33876. BABYLON.Tools.Error("only compressed formats currently supported");
  33877. return;
  33878. }
  33879. else {
  33880. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  33881. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  33882. }
  33883. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  33884. BABYLON.Tools.Error("only 2D textures currently supported");
  33885. return;
  33886. }
  33887. if (this.numberOfArrayElements !== 0) {
  33888. BABYLON.Tools.Error("texture arrays not currently supported");
  33889. return;
  33890. }
  33891. if (this.numberOfFaces !== facesExpected) {
  33892. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  33893. return;
  33894. }
  33895. // we now have a completely validated file, so could use existence of loadType as success
  33896. // would need to make this more elaborate & adjust checks above to support more than one load type
  33897. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  33898. }
  33899. // not as fast hardware based, but will probably never need to use
  33900. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  33901. return ((val & 0xFF) << 24)
  33902. | ((val & 0xFF00) << 8)
  33903. | ((val >> 8) & 0xFF00)
  33904. | ((val >> 24) & 0xFF);
  33905. };
  33906. /**
  33907. * It is assumed that the texture has already been created & is currently bound
  33908. */
  33909. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  33910. switch (this.loadType) {
  33911. case KhronosTextureContainer.COMPRESSED_2D:
  33912. this._upload2DCompressedLevels(gl, loadMipmaps);
  33913. break;
  33914. case KhronosTextureContainer.TEX_2D:
  33915. case KhronosTextureContainer.COMPRESSED_3D:
  33916. case KhronosTextureContainer.TEX_3D:
  33917. }
  33918. };
  33919. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  33920. // initialize width & height for level 1
  33921. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  33922. var width = this.pixelWidth;
  33923. var height = this.pixelHeight;
  33924. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  33925. for (var level = 0; level < mipmapCount; level++) {
  33926. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  33927. for (var face = 0; face < this.numberOfFaces; face++) {
  33928. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  33929. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  33930. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  33931. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  33932. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  33933. }
  33934. width = Math.max(1.0, width * 0.5);
  33935. height = Math.max(1.0, height * 0.5);
  33936. }
  33937. };
  33938. return KhronosTextureContainer;
  33939. }());
  33940. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  33941. // load types
  33942. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  33943. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  33944. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  33945. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  33946. Internals.KhronosTextureContainer = KhronosTextureContainer;
  33947. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  33948. })(BABYLON || (BABYLON = {}));
  33949. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  33950. /// <reference path="babylon.mesh.ts" />
  33951. var BABYLON;
  33952. (function (BABYLON) {
  33953. var GroundMesh = (function (_super) {
  33954. __extends(GroundMesh, _super);
  33955. function GroundMesh(name, scene) {
  33956. var _this = _super.call(this, name, scene) || this;
  33957. _this.generateOctree = false;
  33958. _this._worldInverse = new BABYLON.Matrix();
  33959. return _this;
  33960. }
  33961. GroundMesh.prototype.getClassName = function () {
  33962. return "GroundMesh";
  33963. };
  33964. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  33965. get: function () {
  33966. return Math.min(this._subdivisionsX, this._subdivisionsY);
  33967. },
  33968. enumerable: true,
  33969. configurable: true
  33970. });
  33971. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  33972. get: function () {
  33973. return this._subdivisionsX;
  33974. },
  33975. enumerable: true,
  33976. configurable: true
  33977. });
  33978. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  33979. get: function () {
  33980. return this._subdivisionsY;
  33981. },
  33982. enumerable: true,
  33983. configurable: true
  33984. });
  33985. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  33986. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  33987. this._subdivisionsX = chunksCount;
  33988. this._subdivisionsY = chunksCount;
  33989. this.subdivide(chunksCount);
  33990. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  33991. };
  33992. /**
  33993. * Returns a height (y) value in the Worl system :
  33994. * the ground altitude at the coordinates (x, z) expressed in the World system.
  33995. * Returns the ground y position if (x, z) are outside the ground surface.
  33996. */
  33997. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  33998. var world = this.getWorldMatrix();
  33999. var invMat = BABYLON.Tmp.Matrix[5];
  34000. world.invertToRef(invMat);
  34001. var tmpVect = BABYLON.Tmp.Vector3[8];
  34002. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  34003. x = tmpVect.x;
  34004. z = tmpVect.z;
  34005. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  34006. return this.position.y;
  34007. }
  34008. if (!this._heightQuads || this._heightQuads.length == 0) {
  34009. this._initHeightQuads();
  34010. this._computeHeightQuads();
  34011. }
  34012. var facet = this._getFacetAt(x, z);
  34013. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  34014. // return y in the World system
  34015. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  34016. return tmpVect.y;
  34017. };
  34018. /**
  34019. * Returns a normalized vector (Vector3) orthogonal to the ground
  34020. * at the ground coordinates (x, z) expressed in the World system.
  34021. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  34022. */
  34023. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  34024. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  34025. this.getNormalAtCoordinatesToRef(x, z, normal);
  34026. return normal;
  34027. };
  34028. /**
  34029. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  34030. * at the ground coordinates (x, z) expressed in the World system.
  34031. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  34032. * Returns the GroundMesh.
  34033. */
  34034. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  34035. var world = this.getWorldMatrix();
  34036. var tmpMat = BABYLON.Tmp.Matrix[5];
  34037. world.invertToRef(tmpMat);
  34038. var tmpVect = BABYLON.Tmp.Vector3[8];
  34039. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  34040. x = tmpVect.x;
  34041. z = tmpVect.z;
  34042. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  34043. return this;
  34044. }
  34045. if (!this._heightQuads || this._heightQuads.length == 0) {
  34046. this._initHeightQuads();
  34047. this._computeHeightQuads();
  34048. }
  34049. var facet = this._getFacetAt(x, z);
  34050. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  34051. return this;
  34052. };
  34053. /**
  34054. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  34055. * if the ground has been updated.
  34056. * This can be used in the render loop.
  34057. * Returns the GroundMesh.
  34058. */
  34059. GroundMesh.prototype.updateCoordinateHeights = function () {
  34060. if (!this._heightQuads || this._heightQuads.length == 0) {
  34061. this._initHeightQuads();
  34062. }
  34063. this._computeHeightQuads();
  34064. return this;
  34065. };
  34066. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  34067. GroundMesh.prototype._getFacetAt = function (x, z) {
  34068. // retrieve col and row from x, z coordinates in the ground local system
  34069. var subdivisionsX = this._subdivisionsX;
  34070. var subdivisionsY = this._subdivisionsY;
  34071. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  34072. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  34073. var quad = this._heightQuads[row * this._subdivisionsX + col];
  34074. var facet;
  34075. if (z < quad.slope.x * x + quad.slope.y) {
  34076. facet = quad.facet1;
  34077. }
  34078. else {
  34079. facet = quad.facet2;
  34080. }
  34081. return facet;
  34082. };
  34083. // Creates and populates the heightMap array with "facet" elements :
  34084. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  34085. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  34086. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  34087. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  34088. // Returns the GroundMesh.
  34089. GroundMesh.prototype._initHeightQuads = function () {
  34090. var subdivisionsX = this._subdivisionsX;
  34091. var subdivisionsY = this._subdivisionsY;
  34092. this._heightQuads = new Array();
  34093. for (var row = 0; row < subdivisionsY; row++) {
  34094. for (var col = 0; col < subdivisionsX; col++) {
  34095. 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) };
  34096. this._heightQuads[row * subdivisionsX + col] = quad;
  34097. }
  34098. }
  34099. return this;
  34100. };
  34101. // Compute each quad element values and update the the heightMap array :
  34102. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  34103. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  34104. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  34105. // Returns the GroundMesh.
  34106. GroundMesh.prototype._computeHeightQuads = function () {
  34107. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34108. var v1 = BABYLON.Tmp.Vector3[3];
  34109. var v2 = BABYLON.Tmp.Vector3[2];
  34110. var v3 = BABYLON.Tmp.Vector3[1];
  34111. var v4 = BABYLON.Tmp.Vector3[0];
  34112. var v1v2 = BABYLON.Tmp.Vector3[4];
  34113. var v1v3 = BABYLON.Tmp.Vector3[5];
  34114. var v1v4 = BABYLON.Tmp.Vector3[6];
  34115. var norm1 = BABYLON.Tmp.Vector3[7];
  34116. var norm2 = BABYLON.Tmp.Vector3[8];
  34117. var i = 0;
  34118. var j = 0;
  34119. var k = 0;
  34120. var cd = 0; // 2D slope coefficient : z = cd * x + h
  34121. var h = 0;
  34122. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  34123. var d2 = 0;
  34124. var subdivisionsX = this._subdivisionsX;
  34125. var subdivisionsY = this._subdivisionsY;
  34126. for (var row = 0; row < subdivisionsY; row++) {
  34127. for (var col = 0; col < subdivisionsX; col++) {
  34128. i = col * 3;
  34129. j = row * (subdivisionsX + 1) * 3;
  34130. k = (row + 1) * (subdivisionsX + 1) * 3;
  34131. v1.x = positions[j + i];
  34132. v1.y = positions[j + i + 1];
  34133. v1.z = positions[j + i + 2];
  34134. v2.x = positions[j + i + 3];
  34135. v2.y = positions[j + i + 4];
  34136. v2.z = positions[j + i + 5];
  34137. v3.x = positions[k + i];
  34138. v3.y = positions[k + i + 1];
  34139. v3.z = positions[k + i + 2];
  34140. v4.x = positions[k + i + 3];
  34141. v4.y = positions[k + i + 4];
  34142. v4.z = positions[k + i + 5];
  34143. // 2D slope V1V4
  34144. cd = (v4.z - v1.z) / (v4.x - v1.x);
  34145. h = v1.z - cd * v1.x; // v1 belongs to the slope
  34146. // facet equations :
  34147. // we compute each facet normal vector
  34148. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  34149. // we compute the value d by applying the equation to v1 which belongs to the plane
  34150. // then we store the facet equation in a Vector4
  34151. v2.subtractToRef(v1, v1v2);
  34152. v3.subtractToRef(v1, v1v3);
  34153. v4.subtractToRef(v1, v1v4);
  34154. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  34155. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  34156. norm1.normalize();
  34157. norm2.normalize();
  34158. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  34159. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  34160. var quad = this._heightQuads[row * subdivisionsX + col];
  34161. quad.slope.copyFromFloats(cd, h);
  34162. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  34163. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  34164. }
  34165. }
  34166. return this;
  34167. };
  34168. GroundMesh.prototype.serialize = function (serializationObject) {
  34169. _super.prototype.serialize.call(this, serializationObject);
  34170. serializationObject.subdivisionsX = this._subdivisionsX;
  34171. serializationObject.subdivisionsY = this._subdivisionsY;
  34172. serializationObject.minX = this._minX;
  34173. serializationObject.maxX = this._maxX;
  34174. serializationObject.minZ = this._minZ;
  34175. serializationObject.maxZ = this._maxZ;
  34176. serializationObject.width = this._width;
  34177. serializationObject.height = this._height;
  34178. };
  34179. GroundMesh.Parse = function (parsedMesh, scene) {
  34180. var result = new GroundMesh(parsedMesh.name, scene);
  34181. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  34182. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  34183. result._minX = parsedMesh.minX;
  34184. result._maxX = parsedMesh.maxX;
  34185. result._minZ = parsedMesh.minZ;
  34186. result._maxZ = parsedMesh.maxZ;
  34187. result._width = parsedMesh.width;
  34188. result._height = parsedMesh.height;
  34189. return result;
  34190. };
  34191. return GroundMesh;
  34192. }(BABYLON.Mesh));
  34193. BABYLON.GroundMesh = GroundMesh;
  34194. })(BABYLON || (BABYLON = {}));
  34195. //# sourceMappingURL=babylon.groundMesh.js.map
  34196. var BABYLON;
  34197. (function (BABYLON) {
  34198. /**
  34199. * Creates an instance based on a source mesh.
  34200. */
  34201. var InstancedMesh = (function (_super) {
  34202. __extends(InstancedMesh, _super);
  34203. function InstancedMesh(name, source) {
  34204. var _this = _super.call(this, name, source.getScene()) || this;
  34205. source.instances.push(_this);
  34206. _this._sourceMesh = source;
  34207. _this.position.copyFrom(source.position);
  34208. _this.rotation.copyFrom(source.rotation);
  34209. _this.scaling.copyFrom(source.scaling);
  34210. if (source.rotationQuaternion) {
  34211. _this.rotationQuaternion = source.rotationQuaternion.clone();
  34212. }
  34213. _this.infiniteDistance = source.infiniteDistance;
  34214. _this.setPivotMatrix(source.getPivotMatrix());
  34215. _this.refreshBoundingInfo();
  34216. _this._syncSubMeshes();
  34217. return _this;
  34218. }
  34219. /**
  34220. * Returns the string "InstancedMesh".
  34221. */
  34222. InstancedMesh.prototype.getClassName = function () {
  34223. return "InstancedMesh";
  34224. };
  34225. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  34226. // Methods
  34227. get: function () {
  34228. return this._sourceMesh.receiveShadows;
  34229. },
  34230. enumerable: true,
  34231. configurable: true
  34232. });
  34233. Object.defineProperty(InstancedMesh.prototype, "material", {
  34234. get: function () {
  34235. return this._sourceMesh.material;
  34236. },
  34237. enumerable: true,
  34238. configurable: true
  34239. });
  34240. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  34241. get: function () {
  34242. return this._sourceMesh.visibility;
  34243. },
  34244. enumerable: true,
  34245. configurable: true
  34246. });
  34247. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  34248. get: function () {
  34249. return this._sourceMesh.skeleton;
  34250. },
  34251. enumerable: true,
  34252. configurable: true
  34253. });
  34254. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  34255. get: function () {
  34256. return this._sourceMesh.renderingGroupId;
  34257. },
  34258. enumerable: true,
  34259. configurable: true
  34260. });
  34261. /**
  34262. * Returns the total number of vertices (integer).
  34263. */
  34264. InstancedMesh.prototype.getTotalVertices = function () {
  34265. return this._sourceMesh.getTotalVertices();
  34266. };
  34267. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  34268. get: function () {
  34269. return this._sourceMesh;
  34270. },
  34271. enumerable: true,
  34272. configurable: true
  34273. });
  34274. /**
  34275. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  34276. */
  34277. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  34278. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  34279. };
  34280. /**
  34281. * Sets the vertex data of the mesh geometry for the requested `kind`.
  34282. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  34283. * The `data` are either a numeric array either a Float32Array.
  34284. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  34285. * 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).
  34286. * Note that a new underlying VertexBuffer object is created each call.
  34287. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  34288. *
  34289. * Possible `kind` values :
  34290. * - BABYLON.VertexBuffer.PositionKind
  34291. * - BABYLON.VertexBuffer.UVKind
  34292. * - BABYLON.VertexBuffer.UV2Kind
  34293. * - BABYLON.VertexBuffer.UV3Kind
  34294. * - BABYLON.VertexBuffer.UV4Kind
  34295. * - BABYLON.VertexBuffer.UV5Kind
  34296. * - BABYLON.VertexBuffer.UV6Kind
  34297. * - BABYLON.VertexBuffer.ColorKind
  34298. * - BABYLON.VertexBuffer.MatricesIndicesKind
  34299. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  34300. * - BABYLON.VertexBuffer.MatricesWeightsKind
  34301. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  34302. *
  34303. * Returns the Mesh.
  34304. */
  34305. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34306. if (this.sourceMesh) {
  34307. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  34308. }
  34309. return this.sourceMesh;
  34310. };
  34311. /**
  34312. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  34313. * If the mesh has no geometry, it is simply returned as it is.
  34314. * The `data` are either a numeric array either a Float32Array.
  34315. * No new underlying VertexBuffer object is created.
  34316. * 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.
  34317. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  34318. *
  34319. * Possible `kind` values :
  34320. * - BABYLON.VertexBuffer.PositionKind
  34321. * - BABYLON.VertexBuffer.UVKind
  34322. * - BABYLON.VertexBuffer.UV2Kind
  34323. * - BABYLON.VertexBuffer.UV3Kind
  34324. * - BABYLON.VertexBuffer.UV4Kind
  34325. * - BABYLON.VertexBuffer.UV5Kind
  34326. * - BABYLON.VertexBuffer.UV6Kind
  34327. * - BABYLON.VertexBuffer.ColorKind
  34328. * - BABYLON.VertexBuffer.MatricesIndicesKind
  34329. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  34330. * - BABYLON.VertexBuffer.MatricesWeightsKind
  34331. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  34332. *
  34333. * Returns the Mesh.
  34334. */
  34335. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  34336. if (this.sourceMesh) {
  34337. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  34338. }
  34339. return this.sourceMesh;
  34340. };
  34341. /**
  34342. * Sets the mesh indices.
  34343. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  34344. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  34345. * This method creates a new index buffer each call.
  34346. * Returns the Mesh.
  34347. */
  34348. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  34349. if (this.sourceMesh) {
  34350. this.sourceMesh.setIndices(indices, totalVertices);
  34351. }
  34352. return this.sourceMesh;
  34353. };
  34354. /**
  34355. * Boolean : True if the mesh owns the requested kind of data.
  34356. */
  34357. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  34358. return this._sourceMesh.isVerticesDataPresent(kind);
  34359. };
  34360. /**
  34361. * Returns an array of indices (IndicesArray).
  34362. */
  34363. InstancedMesh.prototype.getIndices = function () {
  34364. return this._sourceMesh.getIndices();
  34365. };
  34366. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  34367. get: function () {
  34368. return this._sourceMesh._positions;
  34369. },
  34370. enumerable: true,
  34371. configurable: true
  34372. });
  34373. /**
  34374. * Sets a new updated BoundingInfo to the mesh.
  34375. * Returns the mesh.
  34376. */
  34377. InstancedMesh.prototype.refreshBoundingInfo = function () {
  34378. var meshBB = this._sourceMesh.getBoundingInfo();
  34379. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  34380. this._updateBoundingInfo();
  34381. return this;
  34382. };
  34383. InstancedMesh.prototype._preActivate = function () {
  34384. if (this._currentLOD) {
  34385. this._currentLOD._preActivate();
  34386. }
  34387. return this;
  34388. };
  34389. InstancedMesh.prototype._activate = function (renderId) {
  34390. if (this._currentLOD) {
  34391. this._currentLOD._registerInstanceForRenderId(this, renderId);
  34392. }
  34393. return this;
  34394. };
  34395. /**
  34396. * Returns the current associated LOD AbstractMesh.
  34397. */
  34398. InstancedMesh.prototype.getLOD = function (camera) {
  34399. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  34400. if (this._currentLOD === this.sourceMesh) {
  34401. return this;
  34402. }
  34403. return this._currentLOD;
  34404. };
  34405. InstancedMesh.prototype._syncSubMeshes = function () {
  34406. this.releaseSubMeshes();
  34407. if (this._sourceMesh.subMeshes) {
  34408. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  34409. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  34410. }
  34411. }
  34412. return this;
  34413. };
  34414. InstancedMesh.prototype._generatePointsArray = function () {
  34415. return this._sourceMesh._generatePointsArray();
  34416. };
  34417. /**
  34418. * Creates a new InstancedMesh from the current mesh.
  34419. * - name (string) : the cloned mesh name
  34420. * - newParent (optional Node) : the optional Node to parent the clone to.
  34421. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  34422. *
  34423. * Returns the clone.
  34424. */
  34425. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  34426. var result = this._sourceMesh.createInstance(name);
  34427. // Deep copy
  34428. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  34429. // Bounding info
  34430. this.refreshBoundingInfo();
  34431. // Parent
  34432. if (newParent) {
  34433. result.parent = newParent;
  34434. }
  34435. if (!doNotCloneChildren) {
  34436. // Children
  34437. for (var index = 0; index < this.getScene().meshes.length; index++) {
  34438. var mesh = this.getScene().meshes[index];
  34439. if (mesh.parent === this) {
  34440. mesh.clone(mesh.name, result);
  34441. }
  34442. }
  34443. }
  34444. result.computeWorldMatrix(true);
  34445. return result;
  34446. };
  34447. /**
  34448. * Disposes the InstancedMesh.
  34449. * Returns nothing.
  34450. */
  34451. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  34452. // Remove from mesh
  34453. var index = this._sourceMesh.instances.indexOf(this);
  34454. this._sourceMesh.instances.splice(index, 1);
  34455. _super.prototype.dispose.call(this, doNotRecurse);
  34456. };
  34457. return InstancedMesh;
  34458. }(BABYLON.AbstractMesh));
  34459. BABYLON.InstancedMesh = InstancedMesh;
  34460. })(BABYLON || (BABYLON = {}));
  34461. //# sourceMappingURL=babylon.instancedMesh.js.map
  34462. /// <reference path="babylon.mesh.ts" />
  34463. var BABYLON;
  34464. (function (BABYLON) {
  34465. var LinesMesh = (function (_super) {
  34466. __extends(LinesMesh, _super);
  34467. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  34468. if (parent === void 0) { parent = null; }
  34469. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  34470. _this.useVertexColor = useVertexColor;
  34471. _this.color = new BABYLON.Color3(1, 1, 1);
  34472. _this.alpha = 1;
  34473. if (source) {
  34474. _this.color = source.color.clone();
  34475. _this.alpha = source.alpha;
  34476. _this.useVertexColor = source.useVertexColor;
  34477. }
  34478. _this._intersectionThreshold = 0.1;
  34479. var options = {
  34480. attributes: [BABYLON.VertexBuffer.PositionKind],
  34481. uniforms: ["world", "viewProjection"],
  34482. needAlphaBlending: false,
  34483. };
  34484. if (!useVertexColor) {
  34485. options.uniforms.push("color");
  34486. options.needAlphaBlending = true;
  34487. }
  34488. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  34489. return _this;
  34490. }
  34491. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  34492. /**
  34493. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  34494. * This margin is expressed in world space coordinates, so its value may vary.
  34495. * Default value is 0.1
  34496. * @returns the intersection Threshold value.
  34497. */
  34498. get: function () {
  34499. return this._intersectionThreshold;
  34500. },
  34501. /**
  34502. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  34503. * This margin is expressed in world space coordinates, so its value may vary.
  34504. * @param value the new threshold to apply
  34505. */
  34506. set: function (value) {
  34507. if (this._intersectionThreshold === value) {
  34508. return;
  34509. }
  34510. this._intersectionThreshold = value;
  34511. if (this.geometry) {
  34512. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  34513. }
  34514. },
  34515. enumerable: true,
  34516. configurable: true
  34517. });
  34518. /**
  34519. * Returns the string "LineMesh"
  34520. */
  34521. LinesMesh.prototype.getClassName = function () {
  34522. return "LinesMesh";
  34523. };
  34524. Object.defineProperty(LinesMesh.prototype, "material", {
  34525. get: function () {
  34526. return this._colorShader;
  34527. },
  34528. enumerable: true,
  34529. configurable: true
  34530. });
  34531. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  34532. get: function () {
  34533. return false;
  34534. },
  34535. enumerable: true,
  34536. configurable: true
  34537. });
  34538. LinesMesh.prototype.createInstance = function (name) {
  34539. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  34540. return null;
  34541. };
  34542. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  34543. // VBOs
  34544. this._geometry._bind(this._colorShader.getEffect());
  34545. // Color
  34546. if (!this.useVertexColor) {
  34547. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  34548. }
  34549. return this;
  34550. };
  34551. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  34552. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  34553. return this;
  34554. }
  34555. var engine = this.getScene().getEngine();
  34556. // Draw order
  34557. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  34558. return this;
  34559. };
  34560. LinesMesh.prototype.dispose = function (doNotRecurse) {
  34561. this._colorShader.dispose();
  34562. _super.prototype.dispose.call(this, doNotRecurse);
  34563. };
  34564. /**
  34565. * Returns a new LineMesh object cloned from the current one.
  34566. */
  34567. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  34568. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  34569. };
  34570. return LinesMesh;
  34571. }(BABYLON.Mesh));
  34572. BABYLON.LinesMesh = LinesMesh;
  34573. })(BABYLON || (BABYLON = {}));
  34574. //# sourceMappingURL=babylon.linesMesh.js.map
  34575. var BABYLON;
  34576. (function (BABYLON) {
  34577. var StandardMaterialDefines = (function (_super) {
  34578. __extends(StandardMaterialDefines, _super);
  34579. function StandardMaterialDefines() {
  34580. var _this = _super.call(this) || this;
  34581. _this.DIFFUSE = false;
  34582. _this.AMBIENT = false;
  34583. _this.OPACITY = false;
  34584. _this.OPACITYRGB = false;
  34585. _this.REFLECTION = false;
  34586. _this.EMISSIVE = false;
  34587. _this.SPECULAR = false;
  34588. _this.BUMP = false;
  34589. _this.PARALLAX = false;
  34590. _this.PARALLAXOCCLUSION = false;
  34591. _this.SPECULAROVERALPHA = false;
  34592. _this.CLIPPLANE = false;
  34593. _this.ALPHATEST = false;
  34594. _this.ALPHAFROMDIFFUSE = false;
  34595. _this.POINTSIZE = false;
  34596. _this.FOG = false;
  34597. _this.SPECULARTERM = false;
  34598. _this.DIFFUSEFRESNEL = false;
  34599. _this.OPACITYFRESNEL = false;
  34600. _this.REFLECTIONFRESNEL = false;
  34601. _this.REFRACTIONFRESNEL = false;
  34602. _this.EMISSIVEFRESNEL = false;
  34603. _this.FRESNEL = false;
  34604. _this.NORMAL = false;
  34605. _this.UV1 = false;
  34606. _this.UV2 = false;
  34607. _this.VERTEXCOLOR = false;
  34608. _this.VERTEXALPHA = false;
  34609. _this.NUM_BONE_INFLUENCERS = 0;
  34610. _this.BonesPerMesh = 0;
  34611. _this.INSTANCES = false;
  34612. _this.GLOSSINESS = false;
  34613. _this.ROUGHNESS = false;
  34614. _this.EMISSIVEASILLUMINATION = false;
  34615. _this.LINKEMISSIVEWITHDIFFUSE = false;
  34616. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  34617. _this.LIGHTMAP = false;
  34618. _this.USELIGHTMAPASSHADOWMAP = false;
  34619. _this.REFLECTIONMAP_3D = false;
  34620. _this.REFLECTIONMAP_SPHERICAL = false;
  34621. _this.REFLECTIONMAP_PLANAR = false;
  34622. _this.REFLECTIONMAP_CUBIC = false;
  34623. _this.REFLECTIONMAP_PROJECTION = false;
  34624. _this.REFLECTIONMAP_SKYBOX = false;
  34625. _this.REFLECTIONMAP_EXPLICIT = false;
  34626. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34627. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34628. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34629. _this.INVERTCUBICMAP = false;
  34630. _this.LOGARITHMICDEPTH = false;
  34631. _this.REFRACTION = false;
  34632. _this.REFRACTIONMAP_3D = false;
  34633. _this.REFLECTIONOVERALPHA = false;
  34634. _this.INVERTNORMALMAPX = false;
  34635. _this.INVERTNORMALMAPY = false;
  34636. _this.TWOSIDEDLIGHTING = false;
  34637. _this.SHADOWFULLFLOAT = false;
  34638. _this.CAMERACOLORGRADING = false;
  34639. _this.CAMERACOLORCURVES = false;
  34640. _this.MORPHTARGETS = false;
  34641. _this.MORPHTARGETS_NORMAL = false;
  34642. _this.MORPHTARGETS_TANGENT = false;
  34643. _this.NUM_MORPH_INFLUENCERS = 0;
  34644. _this.USERIGHTHANDEDSYSTEM = false;
  34645. _this.rebuild();
  34646. return _this;
  34647. }
  34648. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  34649. var modes = [
  34650. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  34651. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  34652. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  34653. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  34654. ];
  34655. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  34656. var mode = modes_1[_i];
  34657. this[mode] = (mode === modeToEnable);
  34658. }
  34659. };
  34660. return StandardMaterialDefines;
  34661. }(BABYLON.MaterialDefines));
  34662. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  34663. var StandardMaterial = (function (_super) {
  34664. __extends(StandardMaterial, _super);
  34665. function StandardMaterial(name, scene) {
  34666. var _this = _super.call(this, name, scene) || this;
  34667. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  34668. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  34669. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  34670. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  34671. _this.specularPower = 64;
  34672. _this._useAlphaFromDiffuseTexture = false;
  34673. _this._useEmissiveAsIllumination = false;
  34674. _this._linkEmissiveWithDiffuse = false;
  34675. _this._useSpecularOverAlpha = false;
  34676. _this._useReflectionOverAlpha = false;
  34677. _this._disableLighting = false;
  34678. _this._useParallax = false;
  34679. _this._useParallaxOcclusion = false;
  34680. _this.parallaxScaleBias = 0.05;
  34681. _this._roughness = 0;
  34682. _this.indexOfRefraction = 0.98;
  34683. _this.invertRefractionY = true;
  34684. _this._useLightmapAsShadowmap = false;
  34685. _this._useReflectionFresnelFromSpecular = false;
  34686. _this._useGlossinessFromSpecularMapAlpha = false;
  34687. _this._maxSimultaneousLights = 4;
  34688. /**
  34689. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  34690. */
  34691. _this._invertNormalMapX = false;
  34692. /**
  34693. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  34694. */
  34695. _this._invertNormalMapY = false;
  34696. /**
  34697. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  34698. */
  34699. _this._twoSidedLighting = false;
  34700. /**
  34701. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34702. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34703. * 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;
  34704. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34705. */
  34706. _this._cameraColorCurves = null;
  34707. _this._renderTargets = new BABYLON.SmartArray(16);
  34708. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  34709. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  34710. _this.getRenderTargetTextures = function () {
  34711. _this._renderTargets.reset();
  34712. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  34713. _this._renderTargets.push(_this._reflectionTexture);
  34714. }
  34715. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  34716. _this._renderTargets.push(_this._refractionTexture);
  34717. }
  34718. return _this._renderTargets;
  34719. };
  34720. return _this;
  34721. }
  34722. StandardMaterial.prototype.getClassName = function () {
  34723. return "StandardMaterial";
  34724. };
  34725. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  34726. get: function () {
  34727. return this._useLogarithmicDepth;
  34728. },
  34729. set: function (value) {
  34730. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  34731. this._markAllSubMeshesAsMiscDirty();
  34732. },
  34733. enumerable: true,
  34734. configurable: true
  34735. });
  34736. StandardMaterial.prototype.needAlphaBlending = function () {
  34737. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  34738. };
  34739. StandardMaterial.prototype.needAlphaTesting = function () {
  34740. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  34741. };
  34742. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  34743. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  34744. };
  34745. StandardMaterial.prototype.getAlphaTestTexture = function () {
  34746. return this._diffuseTexture;
  34747. };
  34748. /**
  34749. * Child classes can use it to update shaders
  34750. */
  34751. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34752. if (this.isFrozen) {
  34753. if (this._wasPreviouslyReady && subMesh.effect) {
  34754. return true;
  34755. }
  34756. }
  34757. if (!subMesh._materialDefines) {
  34758. subMesh._materialDefines = new StandardMaterialDefines();
  34759. }
  34760. var scene = this.getScene();
  34761. var defines = subMesh._materialDefines;
  34762. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  34763. if (defines._renderId === scene.getRenderId()) {
  34764. return true;
  34765. }
  34766. }
  34767. var engine = scene.getEngine();
  34768. // Lights
  34769. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  34770. // Textures
  34771. if (defines._areTexturesDirty) {
  34772. defines._needUVs = false;
  34773. if (scene.texturesEnabled) {
  34774. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34775. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  34776. return false;
  34777. }
  34778. else {
  34779. defines._needUVs = true;
  34780. defines.DIFFUSE = true;
  34781. }
  34782. }
  34783. else {
  34784. defines.DIFFUSE = false;
  34785. }
  34786. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34787. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  34788. return false;
  34789. }
  34790. else {
  34791. defines._needUVs = true;
  34792. defines.AMBIENT = true;
  34793. }
  34794. }
  34795. else {
  34796. defines.AMBIENT = false;
  34797. }
  34798. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34799. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  34800. return false;
  34801. }
  34802. else {
  34803. defines._needUVs = true;
  34804. defines.OPACITY = true;
  34805. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  34806. }
  34807. }
  34808. else {
  34809. defines.OPACITY = false;
  34810. }
  34811. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34812. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  34813. return false;
  34814. }
  34815. else {
  34816. defines._needNormals = true;
  34817. defines.REFLECTION = true;
  34818. defines.ROUGHNESS = (this._roughness > 0);
  34819. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  34820. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  34821. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  34822. switch (this._reflectionTexture.coordinatesMode) {
  34823. case BABYLON.Texture.CUBIC_MODE:
  34824. case BABYLON.Texture.INVCUBIC_MODE:
  34825. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  34826. break;
  34827. case BABYLON.Texture.EXPLICIT_MODE:
  34828. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  34829. break;
  34830. case BABYLON.Texture.PLANAR_MODE:
  34831. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  34832. break;
  34833. case BABYLON.Texture.PROJECTION_MODE:
  34834. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  34835. break;
  34836. case BABYLON.Texture.SKYBOX_MODE:
  34837. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  34838. break;
  34839. case BABYLON.Texture.SPHERICAL_MODE:
  34840. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  34841. break;
  34842. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  34843. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  34844. break;
  34845. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  34846. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  34847. break;
  34848. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  34849. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  34850. break;
  34851. }
  34852. }
  34853. }
  34854. else {
  34855. defines.REFLECTION = false;
  34856. }
  34857. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34858. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  34859. return false;
  34860. }
  34861. else {
  34862. defines._needUVs = true;
  34863. defines.EMISSIVE = true;
  34864. }
  34865. }
  34866. else {
  34867. defines.EMISSIVE = false;
  34868. }
  34869. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34870. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  34871. return false;
  34872. }
  34873. else {
  34874. defines._needUVs = true;
  34875. defines.LIGHTMAP = true;
  34876. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  34877. }
  34878. }
  34879. else {
  34880. defines.LIGHTMAP = false;
  34881. }
  34882. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34883. if (!this._specularTexture.isReadyOrNotBlocking()) {
  34884. return false;
  34885. }
  34886. else {
  34887. defines._needUVs = true;
  34888. defines.SPECULAR = true;
  34889. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  34890. }
  34891. }
  34892. else {
  34893. defines.SPECULAR = false;
  34894. }
  34895. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  34896. // Bump texure can not be none blocking.
  34897. if (!this._bumpTexture.isReady()) {
  34898. return false;
  34899. }
  34900. else {
  34901. defines._needUVs = true;
  34902. defines.BUMP = true;
  34903. defines.INVERTNORMALMAPX = this.invertNormalMapX;
  34904. defines.INVERTNORMALMAPY = this.invertNormalMapY;
  34905. defines.PARALLAX = this._useParallax;
  34906. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  34907. }
  34908. }
  34909. else {
  34910. defines.BUMP = false;
  34911. }
  34912. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34913. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  34914. return false;
  34915. }
  34916. else {
  34917. defines._needUVs = true;
  34918. defines.REFRACTION = true;
  34919. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  34920. }
  34921. }
  34922. else {
  34923. defines.REFRACTION = false;
  34924. }
  34925. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  34926. // Camera Color Grading can not be none blocking.
  34927. if (!this._cameraColorGradingTexture.isReady()) {
  34928. return false;
  34929. }
  34930. else {
  34931. defines.CAMERACOLORGRADING = true;
  34932. }
  34933. }
  34934. else {
  34935. defines.CAMERACOLORGRADING = false;
  34936. }
  34937. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  34938. }
  34939. else {
  34940. defines.DIFFUSE = false;
  34941. defines.AMBIENT = false;
  34942. defines.OPACITY = false;
  34943. defines.REFLECTION = false;
  34944. defines.EMISSIVE = false;
  34945. defines.LIGHTMAP = false;
  34946. defines.BUMP = false;
  34947. defines.REFRACTION = false;
  34948. defines.CAMERACOLORGRADING = false;
  34949. }
  34950. defines.CAMERACOLORCURVES = (this._cameraColorCurves !== undefined && this._cameraColorCurves !== null);
  34951. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  34952. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  34953. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  34954. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  34955. }
  34956. if (defines._areFresnelDirty) {
  34957. if (StandardMaterial.FresnelEnabled) {
  34958. // Fresnel
  34959. if (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled ||
  34960. this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled ||
  34961. this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled ||
  34962. this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled ||
  34963. this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled) {
  34964. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  34965. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  34966. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  34967. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  34968. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  34969. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  34970. defines._needNormals = true;
  34971. defines.FRESNEL = true;
  34972. }
  34973. }
  34974. else {
  34975. defines.FRESNEL = false;
  34976. }
  34977. }
  34978. // Misc.
  34979. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  34980. // Attribs
  34981. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  34982. // Values that need to be evaluated on every frame
  34983. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  34984. if (scene._mirroredCameraPosition && defines.BUMP) {
  34985. defines.INVERTNORMALMAPX = !this.invertNormalMapX;
  34986. defines.INVERTNORMALMAPY = !this.invertNormalMapY;
  34987. defines.markAsUnprocessed();
  34988. }
  34989. // Get correct effect
  34990. if (defines.isDirty) {
  34991. defines.markAsProcessed();
  34992. scene.resetCachedMaterial();
  34993. // Fallbacks
  34994. var fallbacks = new BABYLON.EffectFallbacks();
  34995. if (defines.REFLECTION) {
  34996. fallbacks.addFallback(0, "REFLECTION");
  34997. }
  34998. if (defines.SPECULAR) {
  34999. fallbacks.addFallback(0, "SPECULAR");
  35000. }
  35001. if (defines.BUMP) {
  35002. fallbacks.addFallback(0, "BUMP");
  35003. }
  35004. if (defines.PARALLAX) {
  35005. fallbacks.addFallback(1, "PARALLAX");
  35006. }
  35007. if (defines.PARALLAXOCCLUSION) {
  35008. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  35009. }
  35010. if (defines.SPECULAROVERALPHA) {
  35011. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  35012. }
  35013. if (defines.FOG) {
  35014. fallbacks.addFallback(1, "FOG");
  35015. }
  35016. if (defines.POINTSIZE) {
  35017. fallbacks.addFallback(0, "POINTSIZE");
  35018. }
  35019. if (defines.LOGARITHMICDEPTH) {
  35020. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  35021. }
  35022. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  35023. if (defines.SPECULARTERM) {
  35024. fallbacks.addFallback(0, "SPECULARTERM");
  35025. }
  35026. if (defines.DIFFUSEFRESNEL) {
  35027. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  35028. }
  35029. if (defines.OPACITYFRESNEL) {
  35030. fallbacks.addFallback(2, "OPACITYFRESNEL");
  35031. }
  35032. if (defines.REFLECTIONFRESNEL) {
  35033. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  35034. }
  35035. if (defines.EMISSIVEFRESNEL) {
  35036. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  35037. }
  35038. if (defines.FRESNEL) {
  35039. fallbacks.addFallback(4, "FRESNEL");
  35040. }
  35041. //Attributes
  35042. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35043. if (defines.NORMAL) {
  35044. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35045. }
  35046. if (defines.UV1) {
  35047. attribs.push(BABYLON.VertexBuffer.UVKind);
  35048. }
  35049. if (defines.UV2) {
  35050. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35051. }
  35052. if (defines.VERTEXCOLOR) {
  35053. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35054. }
  35055. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  35056. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  35057. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  35058. var shaderName = "default";
  35059. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  35060. "vFogInfos", "vFogColor", "pointSize",
  35061. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  35062. "mBones",
  35063. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  35064. "depthValues",
  35065. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  35066. "logarithmicDepthConstant"
  35067. ];
  35068. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  35069. var uniformBuffers = ["Material", "Scene"];
  35070. if (defines.CAMERACOLORCURVES) {
  35071. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  35072. }
  35073. if (defines.CAMERACOLORGRADING) {
  35074. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  35075. }
  35076. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  35077. uniformsNames: uniforms,
  35078. uniformBuffersNames: uniformBuffers,
  35079. samplers: samplers,
  35080. defines: defines,
  35081. maxSimultaneousLights: this._maxSimultaneousLights
  35082. });
  35083. if (this.customShaderNameResolve) {
  35084. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  35085. }
  35086. var join = defines.toString();
  35087. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  35088. attributes: attribs,
  35089. uniformsNames: uniforms,
  35090. uniformBuffersNames: uniformBuffers,
  35091. samplers: samplers,
  35092. defines: join,
  35093. fallbacks: fallbacks,
  35094. onCompiled: this.onCompiled,
  35095. onError: this.onError,
  35096. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  35097. }, engine), defines);
  35098. this.buildUniformLayout();
  35099. }
  35100. if (!subMesh.effect.isReady()) {
  35101. return false;
  35102. }
  35103. defines._renderId = scene.getRenderId();
  35104. this._wasPreviouslyReady = true;
  35105. return true;
  35106. };
  35107. StandardMaterial.prototype.buildUniformLayout = function () {
  35108. // Order is important !
  35109. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  35110. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  35111. this._uniformBuffer.addUniform("opacityParts", 4);
  35112. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  35113. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  35114. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  35115. this._uniformBuffer.addUniform("refractionRightColor", 4);
  35116. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  35117. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  35118. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  35119. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  35120. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  35121. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  35122. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  35123. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  35124. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  35125. this._uniformBuffer.addUniform("vBumpInfos", 3);
  35126. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  35127. this._uniformBuffer.addUniform("ambientMatrix", 16);
  35128. this._uniformBuffer.addUniform("opacityMatrix", 16);
  35129. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  35130. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  35131. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  35132. this._uniformBuffer.addUniform("specularMatrix", 16);
  35133. this._uniformBuffer.addUniform("bumpMatrix", 16);
  35134. this._uniformBuffer.addUniform("refractionMatrix", 16);
  35135. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  35136. this._uniformBuffer.addUniform("vSpecularColor", 4);
  35137. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  35138. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  35139. this._uniformBuffer.addUniform("pointSize", 1);
  35140. this._uniformBuffer.create();
  35141. };
  35142. StandardMaterial.prototype.unbind = function () {
  35143. if (this._activeEffect) {
  35144. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  35145. this._activeEffect.setTexture("reflection2DSampler", null);
  35146. }
  35147. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  35148. this._activeEffect.setTexture("refraction2DSampler", null);
  35149. }
  35150. }
  35151. _super.prototype.unbind.call(this);
  35152. };
  35153. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35154. var scene = this.getScene();
  35155. var defines = subMesh._materialDefines;
  35156. if (!defines) {
  35157. return;
  35158. }
  35159. var effect = subMesh.effect;
  35160. this._activeEffect = effect;
  35161. // Matrices
  35162. this.bindOnlyWorldMatrix(world);
  35163. // Bones
  35164. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  35165. if (this._mustRebind(scene, effect, mesh.visibility)) {
  35166. this._uniformBuffer.bindToEffect(effect, "Material");
  35167. this.bindViewProjection(effect);
  35168. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35169. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  35170. // Fresnel
  35171. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  35172. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  35173. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  35174. }
  35175. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  35176. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  35177. }
  35178. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  35179. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  35180. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  35181. }
  35182. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  35183. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  35184. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  35185. }
  35186. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  35187. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  35188. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  35189. }
  35190. }
  35191. // Textures
  35192. if (scene.texturesEnabled) {
  35193. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35194. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  35195. this._uniformBuffer.updateMatrix("diffuseMatrix", this._diffuseTexture.getTextureMatrix());
  35196. }
  35197. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35198. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  35199. this._uniformBuffer.updateMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  35200. }
  35201. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35202. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35203. this._uniformBuffer.updateMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  35204. }
  35205. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35206. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  35207. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  35208. }
  35209. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35210. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35211. this._uniformBuffer.updateMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  35212. }
  35213. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35214. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35215. this._uniformBuffer.updateMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  35216. }
  35217. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35218. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  35219. this._uniformBuffer.updateMatrix("specularMatrix", this._specularTexture.getTextureMatrix());
  35220. }
  35221. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35222. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  35223. this._uniformBuffer.updateMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  35224. }
  35225. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35226. var depth = 1.0;
  35227. if (!this._refractionTexture.isCube) {
  35228. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  35229. if (this._refractionTexture.depth) {
  35230. depth = this._refractionTexture.depth;
  35231. }
  35232. }
  35233. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  35234. }
  35235. }
  35236. // Point size
  35237. if (this.pointsCloud) {
  35238. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35239. }
  35240. if (defines.SPECULARTERM) {
  35241. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  35242. }
  35243. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  35244. // Diffuse
  35245. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  35246. }
  35247. // Textures
  35248. if (scene.texturesEnabled) {
  35249. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35250. effect.setTexture("diffuseSampler", this._diffuseTexture);
  35251. }
  35252. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35253. effect.setTexture("ambientSampler", this._ambientTexture);
  35254. }
  35255. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35256. effect.setTexture("opacitySampler", this._opacityTexture);
  35257. }
  35258. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35259. if (this._reflectionTexture.isCube) {
  35260. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  35261. }
  35262. else {
  35263. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  35264. }
  35265. }
  35266. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35267. effect.setTexture("emissiveSampler", this._emissiveTexture);
  35268. }
  35269. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35270. effect.setTexture("lightmapSampler", this._lightmapTexture);
  35271. }
  35272. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35273. effect.setTexture("specularSampler", this._specularTexture);
  35274. }
  35275. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35276. effect.setTexture("bumpSampler", this._bumpTexture);
  35277. }
  35278. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35279. var depth = 1.0;
  35280. if (this._refractionTexture.isCube) {
  35281. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  35282. }
  35283. else {
  35284. effect.setTexture("refraction2DSampler", this._refractionTexture);
  35285. }
  35286. }
  35287. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  35288. BABYLON.ColorGradingTexture.Bind(this._cameraColorGradingTexture, effect);
  35289. }
  35290. }
  35291. // Clip plane
  35292. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  35293. // Colors
  35294. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  35295. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  35296. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  35297. }
  35298. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  35299. // Lights
  35300. if (scene.lightsEnabled && !this._disableLighting) {
  35301. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  35302. }
  35303. // View
  35304. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  35305. this.bindView(effect);
  35306. }
  35307. // Fog
  35308. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  35309. // Morph targets
  35310. if (defines.NUM_MORPH_INFLUENCERS) {
  35311. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  35312. }
  35313. // Log. depth
  35314. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  35315. // Color Curves
  35316. if (this._cameraColorCurves) {
  35317. BABYLON.ColorCurves.Bind(this._cameraColorCurves, effect);
  35318. }
  35319. }
  35320. this._uniformBuffer.update();
  35321. this._afterBind(mesh, this._activeEffect);
  35322. };
  35323. StandardMaterial.prototype.getAnimatables = function () {
  35324. var results = [];
  35325. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  35326. results.push(this._diffuseTexture);
  35327. }
  35328. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35329. results.push(this._ambientTexture);
  35330. }
  35331. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35332. results.push(this._opacityTexture);
  35333. }
  35334. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35335. results.push(this._reflectionTexture);
  35336. }
  35337. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35338. results.push(this._emissiveTexture);
  35339. }
  35340. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  35341. results.push(this._specularTexture);
  35342. }
  35343. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35344. results.push(this._bumpTexture);
  35345. }
  35346. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  35347. results.push(this._lightmapTexture);
  35348. }
  35349. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  35350. results.push(this._refractionTexture);
  35351. }
  35352. if (this._cameraColorGradingTexture && this._cameraColorGradingTexture.animations && this._cameraColorGradingTexture.animations.length > 0) {
  35353. results.push(this._cameraColorGradingTexture);
  35354. }
  35355. return results;
  35356. };
  35357. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35358. if (forceDisposeTextures) {
  35359. if (this._diffuseTexture) {
  35360. this._diffuseTexture.dispose();
  35361. }
  35362. if (this._ambientTexture) {
  35363. this._ambientTexture.dispose();
  35364. }
  35365. if (this._opacityTexture) {
  35366. this._opacityTexture.dispose();
  35367. }
  35368. if (this._reflectionTexture) {
  35369. this._reflectionTexture.dispose();
  35370. }
  35371. if (this._emissiveTexture) {
  35372. this._emissiveTexture.dispose();
  35373. }
  35374. if (this._specularTexture) {
  35375. this._specularTexture.dispose();
  35376. }
  35377. if (this._bumpTexture) {
  35378. this._bumpTexture.dispose();
  35379. }
  35380. if (this._lightmapTexture) {
  35381. this._lightmapTexture.dispose();
  35382. }
  35383. if (this._refractionTexture) {
  35384. this._refractionTexture.dispose();
  35385. }
  35386. if (this._cameraColorGradingTexture) {
  35387. this._cameraColorGradingTexture.dispose();
  35388. }
  35389. }
  35390. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  35391. };
  35392. StandardMaterial.prototype.clone = function (name) {
  35393. var _this = this;
  35394. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  35395. result.name = name;
  35396. result.id = name;
  35397. return result;
  35398. };
  35399. StandardMaterial.prototype.serialize = function () {
  35400. return BABYLON.SerializationHelper.Serialize(this);
  35401. };
  35402. // Statics
  35403. StandardMaterial.Parse = function (source, scene, rootUrl) {
  35404. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  35405. };
  35406. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  35407. get: function () {
  35408. return StandardMaterial._DiffuseTextureEnabled;
  35409. },
  35410. set: function (value) {
  35411. if (StandardMaterial._DiffuseTextureEnabled === value) {
  35412. return;
  35413. }
  35414. StandardMaterial._DiffuseTextureEnabled = value;
  35415. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35416. },
  35417. enumerable: true,
  35418. configurable: true
  35419. });
  35420. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  35421. get: function () {
  35422. return StandardMaterial._AmbientTextureEnabled;
  35423. },
  35424. set: function (value) {
  35425. if (StandardMaterial._AmbientTextureEnabled === value) {
  35426. return;
  35427. }
  35428. StandardMaterial._AmbientTextureEnabled = value;
  35429. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35430. },
  35431. enumerable: true,
  35432. configurable: true
  35433. });
  35434. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  35435. get: function () {
  35436. return StandardMaterial._OpacityTextureEnabled;
  35437. },
  35438. set: function (value) {
  35439. if (StandardMaterial._OpacityTextureEnabled === value) {
  35440. return;
  35441. }
  35442. StandardMaterial._OpacityTextureEnabled = value;
  35443. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35444. },
  35445. enumerable: true,
  35446. configurable: true
  35447. });
  35448. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  35449. get: function () {
  35450. return StandardMaterial._ReflectionTextureEnabled;
  35451. },
  35452. set: function (value) {
  35453. if (StandardMaterial._ReflectionTextureEnabled === value) {
  35454. return;
  35455. }
  35456. StandardMaterial._ReflectionTextureEnabled = value;
  35457. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35458. },
  35459. enumerable: true,
  35460. configurable: true
  35461. });
  35462. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  35463. get: function () {
  35464. return StandardMaterial._EmissiveTextureEnabled;
  35465. },
  35466. set: function (value) {
  35467. if (StandardMaterial._EmissiveTextureEnabled === value) {
  35468. return;
  35469. }
  35470. StandardMaterial._EmissiveTextureEnabled = value;
  35471. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35472. },
  35473. enumerable: true,
  35474. configurable: true
  35475. });
  35476. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  35477. get: function () {
  35478. return StandardMaterial._SpecularTextureEnabled;
  35479. },
  35480. set: function (value) {
  35481. if (StandardMaterial._SpecularTextureEnabled === value) {
  35482. return;
  35483. }
  35484. StandardMaterial._SpecularTextureEnabled = value;
  35485. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35486. },
  35487. enumerable: true,
  35488. configurable: true
  35489. });
  35490. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  35491. get: function () {
  35492. return StandardMaterial._BumpTextureEnabled;
  35493. },
  35494. set: function (value) {
  35495. if (StandardMaterial._BumpTextureEnabled === value) {
  35496. return;
  35497. }
  35498. StandardMaterial._BumpTextureEnabled = value;
  35499. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35500. },
  35501. enumerable: true,
  35502. configurable: true
  35503. });
  35504. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  35505. get: function () {
  35506. return StandardMaterial._LightmapTextureEnabled;
  35507. },
  35508. set: function (value) {
  35509. if (StandardMaterial._LightmapTextureEnabled === value) {
  35510. return;
  35511. }
  35512. StandardMaterial._LightmapTextureEnabled = value;
  35513. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35514. },
  35515. enumerable: true,
  35516. configurable: true
  35517. });
  35518. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  35519. get: function () {
  35520. return StandardMaterial._RefractionTextureEnabled;
  35521. },
  35522. set: function (value) {
  35523. if (StandardMaterial._RefractionTextureEnabled === value) {
  35524. return;
  35525. }
  35526. StandardMaterial._RefractionTextureEnabled = value;
  35527. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35528. },
  35529. enumerable: true,
  35530. configurable: true
  35531. });
  35532. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  35533. get: function () {
  35534. return StandardMaterial._ColorGradingTextureEnabled;
  35535. },
  35536. set: function (value) {
  35537. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  35538. return;
  35539. }
  35540. StandardMaterial._ColorGradingTextureEnabled = value;
  35541. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35542. },
  35543. enumerable: true,
  35544. configurable: true
  35545. });
  35546. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  35547. get: function () {
  35548. return StandardMaterial._FresnelEnabled;
  35549. },
  35550. set: function (value) {
  35551. if (StandardMaterial._FresnelEnabled === value) {
  35552. return;
  35553. }
  35554. StandardMaterial._FresnelEnabled = value;
  35555. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  35556. },
  35557. enumerable: true,
  35558. configurable: true
  35559. });
  35560. return StandardMaterial;
  35561. }(BABYLON.PushMaterial));
  35562. // Flags used to enable or disable a type of texture for all Standard Materials
  35563. StandardMaterial._DiffuseTextureEnabled = true;
  35564. StandardMaterial._AmbientTextureEnabled = true;
  35565. StandardMaterial._OpacityTextureEnabled = true;
  35566. StandardMaterial._ReflectionTextureEnabled = true;
  35567. StandardMaterial._EmissiveTextureEnabled = true;
  35568. StandardMaterial._SpecularTextureEnabled = true;
  35569. StandardMaterial._BumpTextureEnabled = true;
  35570. StandardMaterial._LightmapTextureEnabled = true;
  35571. StandardMaterial._RefractionTextureEnabled = true;
  35572. StandardMaterial._ColorGradingTextureEnabled = true;
  35573. StandardMaterial._FresnelEnabled = true;
  35574. __decorate([
  35575. BABYLON.serializeAsTexture("diffuseTexture")
  35576. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  35577. __decorate([
  35578. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35579. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  35580. __decorate([
  35581. BABYLON.serializeAsTexture("ambientTexture")
  35582. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  35583. __decorate([
  35584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35585. ], StandardMaterial.prototype, "ambientTexture", void 0);
  35586. __decorate([
  35587. BABYLON.serializeAsTexture("opacityTexture")
  35588. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  35589. __decorate([
  35590. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35591. ], StandardMaterial.prototype, "opacityTexture", void 0);
  35592. __decorate([
  35593. BABYLON.serializeAsTexture("reflectionTexture")
  35594. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  35595. __decorate([
  35596. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35597. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  35598. __decorate([
  35599. BABYLON.serializeAsTexture("emissiveTexture")
  35600. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  35601. __decorate([
  35602. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35603. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  35604. __decorate([
  35605. BABYLON.serializeAsTexture("specularTexture")
  35606. ], StandardMaterial.prototype, "_specularTexture", void 0);
  35607. __decorate([
  35608. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35609. ], StandardMaterial.prototype, "specularTexture", void 0);
  35610. __decorate([
  35611. BABYLON.serializeAsTexture("bumpTexture")
  35612. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  35613. __decorate([
  35614. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35615. ], StandardMaterial.prototype, "bumpTexture", void 0);
  35616. __decorate([
  35617. BABYLON.serializeAsTexture("lightmapTexture")
  35618. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  35619. __decorate([
  35620. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35621. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  35622. __decorate([
  35623. BABYLON.serializeAsTexture("refractionTexture")
  35624. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  35625. __decorate([
  35626. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35627. ], StandardMaterial.prototype, "refractionTexture", void 0);
  35628. __decorate([
  35629. BABYLON.serializeAsColor3("ambient")
  35630. ], StandardMaterial.prototype, "ambientColor", void 0);
  35631. __decorate([
  35632. BABYLON.serializeAsColor3("diffuse")
  35633. ], StandardMaterial.prototype, "diffuseColor", void 0);
  35634. __decorate([
  35635. BABYLON.serializeAsColor3("specular")
  35636. ], StandardMaterial.prototype, "specularColor", void 0);
  35637. __decorate([
  35638. BABYLON.serializeAsColor3("emissive")
  35639. ], StandardMaterial.prototype, "emissiveColor", void 0);
  35640. __decorate([
  35641. BABYLON.serialize()
  35642. ], StandardMaterial.prototype, "specularPower", void 0);
  35643. __decorate([
  35644. BABYLON.serialize("useAlphaFromDiffuseTexture")
  35645. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  35646. __decorate([
  35647. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35648. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  35649. __decorate([
  35650. BABYLON.serialize("useEmissiveAsIllumination")
  35651. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  35652. __decorate([
  35653. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35654. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  35655. __decorate([
  35656. BABYLON.serialize("linkEmissiveWithDiffuse")
  35657. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  35658. __decorate([
  35659. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35660. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  35661. __decorate([
  35662. BABYLON.serialize("useSpecularOverAlpha")
  35663. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  35664. __decorate([
  35665. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35666. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  35667. __decorate([
  35668. BABYLON.serialize("useReflectionOverAlpha")
  35669. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  35670. __decorate([
  35671. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35672. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  35673. __decorate([
  35674. BABYLON.serialize("disableLighting")
  35675. ], StandardMaterial.prototype, "_disableLighting", void 0);
  35676. __decorate([
  35677. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35678. ], StandardMaterial.prototype, "disableLighting", void 0);
  35679. __decorate([
  35680. BABYLON.serialize("useParallax")
  35681. ], StandardMaterial.prototype, "_useParallax", void 0);
  35682. __decorate([
  35683. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35684. ], StandardMaterial.prototype, "useParallax", void 0);
  35685. __decorate([
  35686. BABYLON.serialize("useParallaxOcclusion")
  35687. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  35688. __decorate([
  35689. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35690. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  35691. __decorate([
  35692. BABYLON.serialize()
  35693. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  35694. __decorate([
  35695. BABYLON.serialize("roughness")
  35696. ], StandardMaterial.prototype, "_roughness", void 0);
  35697. __decorate([
  35698. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35699. ], StandardMaterial.prototype, "roughness", void 0);
  35700. __decorate([
  35701. BABYLON.serialize()
  35702. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  35703. __decorate([
  35704. BABYLON.serialize()
  35705. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  35706. __decorate([
  35707. BABYLON.serialize("useLightmapAsShadowmap")
  35708. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  35709. __decorate([
  35710. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35711. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  35712. __decorate([
  35713. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  35714. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  35715. __decorate([
  35716. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35717. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  35718. __decorate([
  35719. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  35720. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  35721. __decorate([
  35722. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35723. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  35724. __decorate([
  35725. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  35726. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  35727. __decorate([
  35728. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35729. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  35730. __decorate([
  35731. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  35732. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  35733. __decorate([
  35734. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35735. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  35736. __decorate([
  35737. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  35738. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  35739. __decorate([
  35740. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35741. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  35742. __decorate([
  35743. BABYLON.serialize("useReflectionFresnelFromSpecular")
  35744. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  35745. __decorate([
  35746. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35747. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  35748. __decorate([
  35749. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  35750. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  35751. __decorate([
  35752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35753. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  35754. __decorate([
  35755. BABYLON.serialize("maxSimultaneousLights")
  35756. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  35757. __decorate([
  35758. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35759. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  35760. __decorate([
  35761. BABYLON.serialize("invertNormalMapX")
  35762. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  35763. __decorate([
  35764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35765. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  35766. __decorate([
  35767. BABYLON.serialize("invertNormalMapY")
  35768. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  35769. __decorate([
  35770. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35771. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  35772. __decorate([
  35773. BABYLON.serialize("twoSidedLighting")
  35774. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  35775. __decorate([
  35776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35777. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  35778. __decorate([
  35779. BABYLON.serializeAsTexture("cameraColorGradingTexture")
  35780. ], StandardMaterial.prototype, "_cameraColorGradingTexture", void 0);
  35781. __decorate([
  35782. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35783. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  35784. __decorate([
  35785. BABYLON.serializeAsColorCurves("cameraColorCurves")
  35786. ], StandardMaterial.prototype, "_cameraColorCurves", void 0);
  35787. __decorate([
  35788. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35789. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  35790. __decorate([
  35791. BABYLON.serialize()
  35792. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  35793. BABYLON.StandardMaterial = StandardMaterial;
  35794. })(BABYLON || (BABYLON = {}));
  35795. //# sourceMappingURL=babylon.standardMaterial.js.map
  35796. var BABYLON;
  35797. (function (BABYLON) {
  35798. /**
  35799. * This class implement a typical dictionary using a string as key and the generic type T as value.
  35800. * The underlying implementation relies on an associative array to ensure the best performances.
  35801. * The value can be anything including 'null' but except 'undefined'
  35802. */
  35803. var StringDictionary = (function () {
  35804. function StringDictionary() {
  35805. this._count = 0;
  35806. this._data = {};
  35807. }
  35808. /**
  35809. * This will clear this dictionary and copy the content from the 'source' one.
  35810. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  35811. * @param source the dictionary to take the content from and copy to this dictionary
  35812. */
  35813. StringDictionary.prototype.copyFrom = function (source) {
  35814. var _this = this;
  35815. this.clear();
  35816. source.forEach(function (t, v) { return _this.add(t, v); });
  35817. };
  35818. /**
  35819. * Get a value based from its key
  35820. * @param key the given key to get the matching value from
  35821. * @return the value if found, otherwise undefined is returned
  35822. */
  35823. StringDictionary.prototype.get = function (key) {
  35824. var val = this._data[key];
  35825. if (val !== undefined) {
  35826. return val;
  35827. }
  35828. return undefined;
  35829. };
  35830. /**
  35831. * Get a value from its key or add it if it doesn't exist.
  35832. * This method will ensure you that a given key/data will be present in the dictionary.
  35833. * @param key the given key to get the matching value from
  35834. * @param factory the factory that will create the value if the key is not present in the dictionary.
  35835. * The factory will only be invoked if there's no data for the given key.
  35836. * @return the value corresponding to the key.
  35837. */
  35838. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  35839. var val = this.get(key);
  35840. if (val !== undefined) {
  35841. return val;
  35842. }
  35843. val = factory(key);
  35844. if (val) {
  35845. this.add(key, val);
  35846. }
  35847. return val;
  35848. };
  35849. /**
  35850. * Get a value from its key if present in the dictionary otherwise add it
  35851. * @param key the key to get the value from
  35852. * @param val if there's no such key/value pair in the dictionary add it with this value
  35853. * @return the value corresponding to the key
  35854. */
  35855. StringDictionary.prototype.getOrAdd = function (key, val) {
  35856. var curVal = this.get(key);
  35857. if (curVal !== undefined) {
  35858. return curVal;
  35859. }
  35860. this.add(key, val);
  35861. return val;
  35862. };
  35863. /**
  35864. * Check if there's a given key in the dictionary
  35865. * @param key the key to check for
  35866. * @return true if the key is present, false otherwise
  35867. */
  35868. StringDictionary.prototype.contains = function (key) {
  35869. return this._data[key] !== undefined;
  35870. };
  35871. /**
  35872. * Add a new key and its corresponding value
  35873. * @param key the key to add
  35874. * @param value the value corresponding to the key
  35875. * @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
  35876. */
  35877. StringDictionary.prototype.add = function (key, value) {
  35878. if (this._data[key] !== undefined) {
  35879. return false;
  35880. }
  35881. this._data[key] = value;
  35882. ++this._count;
  35883. return true;
  35884. };
  35885. StringDictionary.prototype.set = function (key, value) {
  35886. if (this._data[key] === undefined) {
  35887. return false;
  35888. }
  35889. this._data[key] = value;
  35890. return true;
  35891. };
  35892. /**
  35893. * Get the element of the given key and remove it from the dictionary
  35894. * @param key
  35895. */
  35896. StringDictionary.prototype.getAndRemove = function (key) {
  35897. var val = this.get(key);
  35898. if (val !== undefined) {
  35899. delete this._data[key];
  35900. --this._count;
  35901. return val;
  35902. }
  35903. return null;
  35904. };
  35905. /**
  35906. * Remove a key/value from the dictionary.
  35907. * @param key the key to remove
  35908. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  35909. */
  35910. StringDictionary.prototype.remove = function (key) {
  35911. if (this.contains(key)) {
  35912. delete this._data[key];
  35913. --this._count;
  35914. return true;
  35915. }
  35916. return false;
  35917. };
  35918. /**
  35919. * Clear the whole content of the dictionary
  35920. */
  35921. StringDictionary.prototype.clear = function () {
  35922. this._data = {};
  35923. this._count = 0;
  35924. };
  35925. Object.defineProperty(StringDictionary.prototype, "count", {
  35926. get: function () {
  35927. return this._count;
  35928. },
  35929. enumerable: true,
  35930. configurable: true
  35931. });
  35932. /**
  35933. * Execute a callback on each key/val of the dictionary.
  35934. * Note that you can remove any element in this dictionary in the callback implementation
  35935. * @param callback the callback to execute on a given key/value pair
  35936. */
  35937. StringDictionary.prototype.forEach = function (callback) {
  35938. for (var cur in this._data) {
  35939. var val = this._data[cur];
  35940. callback(cur, val);
  35941. }
  35942. };
  35943. /**
  35944. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  35945. * If the callback returns null or undefined the method will iterate to the next key/value pair
  35946. * Note that you can remove any element in this dictionary in the callback implementation
  35947. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  35948. */
  35949. StringDictionary.prototype.first = function (callback) {
  35950. for (var cur in this._data) {
  35951. var val = this._data[cur];
  35952. var res = callback(cur, val);
  35953. if (res) {
  35954. return res;
  35955. }
  35956. }
  35957. return null;
  35958. };
  35959. return StringDictionary;
  35960. }());
  35961. BABYLON.StringDictionary = StringDictionary;
  35962. })(BABYLON || (BABYLON = {}));
  35963. //# sourceMappingURL=babylon.stringDictionary.js.map
  35964. var BABYLON;
  35965. (function (BABYLON) {
  35966. var DynamicFloatArrayElementInfo = (function () {
  35967. function DynamicFloatArrayElementInfo() {
  35968. }
  35969. return DynamicFloatArrayElementInfo;
  35970. }());
  35971. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  35972. /**
  35973. * 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.
  35974. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  35975. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  35976. * 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.
  35977. * 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.
  35978. * 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".
  35979. */
  35980. var DynamicFloatArray = (function () {
  35981. /**
  35982. * Construct an instance of the dynamic float array
  35983. * @param stride size of one element in float (i.e. not bytes!)
  35984. * @param initialElementCount the number of available entries at construction
  35985. */
  35986. function DynamicFloatArray(stride, initialElementCount) {
  35987. this.compareValueOffset = null;
  35988. this.sortingAscending = true;
  35989. this._stride = stride;
  35990. this.buffer = new Float32Array(stride * initialElementCount);
  35991. this._lastUsed = 0;
  35992. this._firstFree = 0;
  35993. this._allEntries = new Array(initialElementCount);
  35994. this._freeEntries = new Array(initialElementCount);
  35995. for (var i = 0; i < initialElementCount; i++) {
  35996. var element = new DynamicFloatArrayElementInfo();
  35997. element.offset = i * stride;
  35998. this._allEntries[i] = element;
  35999. this._freeEntries[initialElementCount - i - 1] = element;
  36000. }
  36001. }
  36002. /**
  36003. * Allocate an element in the array.
  36004. * @return the element info instance that contains the offset into the main buffer of the element's location.
  36005. * Beware, this offset may change when you call pack()
  36006. */
  36007. DynamicFloatArray.prototype.allocElement = function () {
  36008. if (this._freeEntries.length === 0) {
  36009. this._growBuffer();
  36010. }
  36011. var el = this._freeEntries.pop();
  36012. this._lastUsed = Math.max(el.offset, this._lastUsed);
  36013. if (el.offset === this._firstFree) {
  36014. if (this._freeEntries.length > 0) {
  36015. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  36016. }
  36017. else {
  36018. this._firstFree += this._stride;
  36019. }
  36020. }
  36021. return el;
  36022. };
  36023. /**
  36024. * Free the element corresponding to the given element info
  36025. * @param elInfo the element that describe the allocated element
  36026. */
  36027. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  36028. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  36029. this._freeEntries.push(elInfo);
  36030. };
  36031. /**
  36032. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  36033. * 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().
  36034. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  36035. */
  36036. DynamicFloatArray.prototype.pack = function () {
  36037. // no free slot? no need to pack
  36038. if (this._freeEntries.length === 0) {
  36039. return this.buffer;
  36040. }
  36041. // If the buffer is already packed the last used will always be lower than the first free
  36042. // 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.
  36043. if (this._lastUsed < this._firstFree) {
  36044. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  36045. return elementsBuffer_1;
  36046. }
  36047. var s = this._stride;
  36048. // 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
  36049. var lastFree = new DynamicFloatArrayElementInfo();
  36050. lastFree.offset = this.totalElementCount * s;
  36051. this._freeEntries.push(lastFree);
  36052. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  36053. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  36054. var firstFreeSlotOffset = sortedFree[0].offset;
  36055. var freeZoneSize = 1;
  36056. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  36057. var prevOffset = sortedFree[0].offset;
  36058. for (var i = 1; i < sortedFree.length; i++) {
  36059. // 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
  36060. if (firstFreeSlotOffset >= occupiedZoneSize) {
  36061. break;
  36062. }
  36063. var curFree = sortedFree[i];
  36064. var curOffset = curFree.offset;
  36065. // Compute the distance between this offset and the previous
  36066. var distance = curOffset - prevOffset;
  36067. // If the distance is the stride size, they are adjacent, it good, move to the next
  36068. if (distance === s) {
  36069. // Free zone is one element bigger
  36070. ++freeZoneSize;
  36071. // as we're about to iterate to the next, the cur becomes the previous...
  36072. prevOffset = curOffset;
  36073. continue;
  36074. }
  36075. // Distance is bigger, which means there's x element between the previous free and this one
  36076. var usedRange = (distance / s) - 1;
  36077. // Two cases the free zone is smaller than the data to move or bigger
  36078. // Copy what can fit in the free zone
  36079. var curMoveOffset = curOffset - s;
  36080. var copyCount = Math.min(freeZoneSize, usedRange);
  36081. for (var j = 0; j < copyCount; j++) {
  36082. var freeI = firstFreeSlotOffset / s;
  36083. var curI = curMoveOffset / s;
  36084. var moveEl = sortedAll[curI];
  36085. this._moveElement(moveEl, firstFreeSlotOffset);
  36086. var replacedEl = sortedAll[freeI];
  36087. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  36088. replacedEl.offset = curMoveOffset;
  36089. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  36090. sortedAll[freeI] = moveEl;
  36091. sortedAll[curI] = replacedEl;
  36092. curMoveOffset -= s;
  36093. firstFreeSlotOffset += s;
  36094. }
  36095. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  36096. if (freeZoneSize <= usedRange) {
  36097. firstFreeSlotOffset = curMoveOffset + s;
  36098. freeZoneSize = 1 + copyCount;
  36099. }
  36100. else {
  36101. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  36102. }
  36103. // as we're about to iterate to the next, the cur becomes the previous...
  36104. prevOffset = curOffset;
  36105. }
  36106. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  36107. this._lastUsed = firstFreeSlotOffset - s;
  36108. this._firstFree = firstFreeSlotOffset;
  36109. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  36110. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  36111. this._allEntries = sortedAll;
  36112. return elementsBuffer;
  36113. };
  36114. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  36115. for (var i = 0; i < this._stride; i++) {
  36116. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  36117. }
  36118. element.offset = destOffset;
  36119. };
  36120. DynamicFloatArray.prototype._growBuffer = function () {
  36121. // Allocate the new buffer with 50% more entries, copy the content of the current one
  36122. var newElCount = Math.floor(this.totalElementCount * 1.5);
  36123. var newBuffer = new Float32Array(newElCount * this._stride);
  36124. newBuffer.set(this.buffer);
  36125. var curCount = this.totalElementCount;
  36126. var addedCount = newElCount - this.totalElementCount;
  36127. for (var i = 0; i < addedCount; i++) {
  36128. var element = new DynamicFloatArrayElementInfo();
  36129. element.offset = (curCount + i) * this.stride;
  36130. this._allEntries.push(element);
  36131. this._freeEntries[addedCount - i - 1] = element;
  36132. }
  36133. this._firstFree = curCount * this.stride;
  36134. this.buffer = newBuffer;
  36135. };
  36136. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  36137. /**
  36138. * Get the total count of entries that can fit in the current buffer
  36139. * @returns the elements count
  36140. */
  36141. get: function () {
  36142. return this._allEntries.length;
  36143. },
  36144. enumerable: true,
  36145. configurable: true
  36146. });
  36147. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  36148. /**
  36149. * Get the count of free entries that can still be allocated without resizing the buffer
  36150. * @returns the free elements count
  36151. */
  36152. get: function () {
  36153. return this._freeEntries.length;
  36154. },
  36155. enumerable: true,
  36156. configurable: true
  36157. });
  36158. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  36159. /**
  36160. * Get the count of allocated elements
  36161. * @returns the allocated elements count
  36162. */
  36163. get: function () {
  36164. return this._allEntries.length - this._freeEntries.length;
  36165. },
  36166. enumerable: true,
  36167. configurable: true
  36168. });
  36169. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  36170. /**
  36171. * Return the size of one element in float
  36172. * @returns the size in float
  36173. */
  36174. get: function () {
  36175. return this._stride;
  36176. },
  36177. enumerable: true,
  36178. configurable: true
  36179. });
  36180. DynamicFloatArray.prototype.sort = function () {
  36181. var _this = this;
  36182. if (!this.compareValueOffset) {
  36183. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  36184. }
  36185. var count = this.usedElementCount;
  36186. // Do we have to (re)create the sort table?
  36187. if (!this._sortTable || this._sortTable.length < count) {
  36188. // 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...
  36189. var newCount = Math.min(this.totalElementCount, count * 2);
  36190. this._sortTable = new Array(newCount);
  36191. }
  36192. if (!this._sortedTable || this._sortedTable.length !== count) {
  36193. this._sortedTable = new Array(count);
  36194. }
  36195. // Because, you know...
  36196. this.pack();
  36197. //let stride = this.stride;
  36198. //for (let i = 0; i < count; i++) {
  36199. // let si = this._sortTable[i];
  36200. // if (!si) {
  36201. // si = new SortInfo();
  36202. // this._sortTable[i] = si;
  36203. // }
  36204. // si.entry = this._allEntries[i];
  36205. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  36206. // si.swapedOffset = null;
  36207. // this._sortedTable[i] = si;
  36208. //}
  36209. var curOffset = 0;
  36210. var stride = this.stride;
  36211. for (var i = 0; i < count; i++, curOffset += stride) {
  36212. var si = this._sortTable[i];
  36213. if (!si) {
  36214. si = new SortInfo();
  36215. this._sortTable[i] = si;
  36216. }
  36217. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  36218. si.offset = curOffset;
  36219. si.swapedOffset = null;
  36220. this._sortedTable[i] = si;
  36221. }
  36222. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  36223. if (this.sortingAscending) {
  36224. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  36225. }
  36226. else {
  36227. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  36228. }
  36229. var swapElements = function (src, dst) {
  36230. for (var i = 0; i < stride; i++) {
  36231. var tps = _this.buffer[dst + i];
  36232. _this.buffer[dst + i] = _this.buffer[src + i];
  36233. _this.buffer[src + i] = tps;
  36234. }
  36235. };
  36236. // 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:
  36237. // 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),
  36238. // and I still want something with a good algorithm complexity.
  36239. // 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,
  36240. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  36241. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  36242. // 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
  36243. // until we find a SortInfo object without a swapedOffset which means we got the right location
  36244. // 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
  36245. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  36246. for (var i = 0; i < count; i++) {
  36247. // Get the element to move
  36248. var sourceSI = this._sortedTable[i];
  36249. var destSI = this._sortTable[i];
  36250. var sourceOff = sourceSI.offset;
  36251. // If the source changed location, find the new one
  36252. if (sourceSI.swapedOffset) {
  36253. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  36254. var curSI = sourceSI;
  36255. while (curSI.swapedOffset) {
  36256. curSI = this._sortTable[curSI.swapedOffset / stride];
  36257. }
  36258. // Finally get the right location
  36259. sourceOff = curSI.offset;
  36260. }
  36261. // Tag the element being replaced with its new location
  36262. destSI.swapedOffset = sourceOff;
  36263. // Swap elements (only if needed)
  36264. if (sourceOff !== destSI.offset) {
  36265. swapElements(sourceOff, destSI.offset);
  36266. }
  36267. // Update the offset in the corresponding DFAE
  36268. //sourceSI.entry.offset = destSI.entry.offset;
  36269. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  36270. }
  36271. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  36272. return true;
  36273. };
  36274. return DynamicFloatArray;
  36275. }());
  36276. BABYLON.DynamicFloatArray = DynamicFloatArray;
  36277. var SortInfo = (function () {
  36278. function SortInfo() {
  36279. this.compareData = this.offset = this.swapedOffset = null;
  36280. }
  36281. return SortInfo;
  36282. }());
  36283. })(BABYLON || (BABYLON = {}));
  36284. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  36285. var BABYLON;
  36286. (function (BABYLON) {
  36287. var Condition = (function () {
  36288. function Condition(actionManager) {
  36289. this._actionManager = actionManager;
  36290. }
  36291. Condition.prototype.isValid = function () {
  36292. return true;
  36293. };
  36294. Condition.prototype._getProperty = function (propertyPath) {
  36295. return this._actionManager._getProperty(propertyPath);
  36296. };
  36297. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  36298. return this._actionManager._getEffectiveTarget(target, propertyPath);
  36299. };
  36300. Condition.prototype.serialize = function () {
  36301. };
  36302. Condition.prototype._serialize = function (serializedCondition) {
  36303. return {
  36304. type: 2,
  36305. children: [],
  36306. name: serializedCondition.name,
  36307. properties: serializedCondition.properties
  36308. };
  36309. };
  36310. return Condition;
  36311. }());
  36312. BABYLON.Condition = Condition;
  36313. var ValueCondition = (function (_super) {
  36314. __extends(ValueCondition, _super);
  36315. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  36316. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  36317. var _this = _super.call(this, actionManager) || this;
  36318. _this.propertyPath = propertyPath;
  36319. _this.value = value;
  36320. _this.operator = operator;
  36321. _this._target = target;
  36322. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  36323. _this._property = _this._getProperty(_this.propertyPath);
  36324. return _this;
  36325. }
  36326. Object.defineProperty(ValueCondition, "IsEqual", {
  36327. get: function () {
  36328. return ValueCondition._IsEqual;
  36329. },
  36330. enumerable: true,
  36331. configurable: true
  36332. });
  36333. Object.defineProperty(ValueCondition, "IsDifferent", {
  36334. get: function () {
  36335. return ValueCondition._IsDifferent;
  36336. },
  36337. enumerable: true,
  36338. configurable: true
  36339. });
  36340. Object.defineProperty(ValueCondition, "IsGreater", {
  36341. get: function () {
  36342. return ValueCondition._IsGreater;
  36343. },
  36344. enumerable: true,
  36345. configurable: true
  36346. });
  36347. Object.defineProperty(ValueCondition, "IsLesser", {
  36348. get: function () {
  36349. return ValueCondition._IsLesser;
  36350. },
  36351. enumerable: true,
  36352. configurable: true
  36353. });
  36354. // Methods
  36355. ValueCondition.prototype.isValid = function () {
  36356. switch (this.operator) {
  36357. case ValueCondition.IsGreater:
  36358. return this._effectiveTarget[this._property] > this.value;
  36359. case ValueCondition.IsLesser:
  36360. return this._effectiveTarget[this._property] < this.value;
  36361. case ValueCondition.IsEqual:
  36362. case ValueCondition.IsDifferent:
  36363. var check;
  36364. if (this.value.equals) {
  36365. check = this.value.equals(this._effectiveTarget[this._property]);
  36366. }
  36367. else {
  36368. check = this.value === this._effectiveTarget[this._property];
  36369. }
  36370. return this.operator === ValueCondition.IsEqual ? check : !check;
  36371. }
  36372. return false;
  36373. };
  36374. ValueCondition.prototype.serialize = function () {
  36375. return this._serialize({
  36376. name: "ValueCondition",
  36377. properties: [
  36378. BABYLON.Action._GetTargetProperty(this._target),
  36379. { name: "propertyPath", value: this.propertyPath },
  36380. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  36381. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  36382. ]
  36383. });
  36384. };
  36385. ValueCondition.GetOperatorName = function (operator) {
  36386. switch (operator) {
  36387. case ValueCondition._IsEqual: return "IsEqual";
  36388. case ValueCondition._IsDifferent: return "IsDifferent";
  36389. case ValueCondition._IsGreater: return "IsGreater";
  36390. case ValueCondition._IsLesser: return "IsLesser";
  36391. default: return "";
  36392. }
  36393. };
  36394. return ValueCondition;
  36395. }(Condition));
  36396. // Statics
  36397. ValueCondition._IsEqual = 0;
  36398. ValueCondition._IsDifferent = 1;
  36399. ValueCondition._IsGreater = 2;
  36400. ValueCondition._IsLesser = 3;
  36401. BABYLON.ValueCondition = ValueCondition;
  36402. var PredicateCondition = (function (_super) {
  36403. __extends(PredicateCondition, _super);
  36404. function PredicateCondition(actionManager, predicate) {
  36405. var _this = _super.call(this, actionManager) || this;
  36406. _this.predicate = predicate;
  36407. return _this;
  36408. }
  36409. PredicateCondition.prototype.isValid = function () {
  36410. return this.predicate();
  36411. };
  36412. return PredicateCondition;
  36413. }(Condition));
  36414. BABYLON.PredicateCondition = PredicateCondition;
  36415. var StateCondition = (function (_super) {
  36416. __extends(StateCondition, _super);
  36417. function StateCondition(actionManager, target, value) {
  36418. var _this = _super.call(this, actionManager) || this;
  36419. _this.value = value;
  36420. _this._target = target;
  36421. return _this;
  36422. }
  36423. // Methods
  36424. StateCondition.prototype.isValid = function () {
  36425. return this._target.state === this.value;
  36426. };
  36427. StateCondition.prototype.serialize = function () {
  36428. return this._serialize({
  36429. name: "StateCondition",
  36430. properties: [
  36431. BABYLON.Action._GetTargetProperty(this._target),
  36432. { name: "value", value: this.value }
  36433. ]
  36434. });
  36435. };
  36436. return StateCondition;
  36437. }(Condition));
  36438. BABYLON.StateCondition = StateCondition;
  36439. })(BABYLON || (BABYLON = {}));
  36440. //# sourceMappingURL=babylon.condition.js.map
  36441. var BABYLON;
  36442. (function (BABYLON) {
  36443. var Action = (function () {
  36444. function Action(triggerOptions, condition) {
  36445. this.triggerOptions = triggerOptions;
  36446. if (triggerOptions.parameter) {
  36447. this.trigger = triggerOptions.trigger;
  36448. this._triggerParameter = triggerOptions.parameter;
  36449. }
  36450. else {
  36451. this.trigger = triggerOptions;
  36452. }
  36453. this._nextActiveAction = this;
  36454. this._condition = condition;
  36455. }
  36456. // Methods
  36457. Action.prototype._prepare = function () {
  36458. };
  36459. Action.prototype.getTriggerParameter = function () {
  36460. return this._triggerParameter;
  36461. };
  36462. Action.prototype._executeCurrent = function (evt) {
  36463. if (this._nextActiveAction._condition) {
  36464. var condition = this._nextActiveAction._condition;
  36465. var currentRenderId = this._actionManager.getScene().getRenderId();
  36466. // We cache the current evaluation for the current frame
  36467. if (condition._evaluationId === currentRenderId) {
  36468. if (!condition._currentResult) {
  36469. return;
  36470. }
  36471. }
  36472. else {
  36473. condition._evaluationId = currentRenderId;
  36474. if (!condition.isValid()) {
  36475. condition._currentResult = false;
  36476. return;
  36477. }
  36478. condition._currentResult = true;
  36479. }
  36480. }
  36481. this._nextActiveAction.execute(evt);
  36482. this.skipToNextActiveAction();
  36483. };
  36484. Action.prototype.execute = function (evt) {
  36485. };
  36486. Action.prototype.skipToNextActiveAction = function () {
  36487. if (this._nextActiveAction._child) {
  36488. if (!this._nextActiveAction._child._actionManager) {
  36489. this._nextActiveAction._child._actionManager = this._actionManager;
  36490. }
  36491. this._nextActiveAction = this._nextActiveAction._child;
  36492. }
  36493. else {
  36494. this._nextActiveAction = this;
  36495. }
  36496. };
  36497. Action.prototype.then = function (action) {
  36498. this._child = action;
  36499. action._actionManager = this._actionManager;
  36500. action._prepare();
  36501. return action;
  36502. };
  36503. Action.prototype._getProperty = function (propertyPath) {
  36504. return this._actionManager._getProperty(propertyPath);
  36505. };
  36506. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  36507. return this._actionManager._getEffectiveTarget(target, propertyPath);
  36508. };
  36509. Action.prototype.serialize = function (parent) {
  36510. };
  36511. // Called by BABYLON.Action objects in serialize(...). Internal use
  36512. Action.prototype._serialize = function (serializedAction, parent) {
  36513. var serializationObject = {
  36514. type: 1,
  36515. children: [],
  36516. name: serializedAction.name,
  36517. properties: serializedAction.properties || []
  36518. };
  36519. // Serialize child
  36520. if (this._child) {
  36521. this._child.serialize(serializationObject);
  36522. }
  36523. // Check if "this" has a condition
  36524. if (this._condition) {
  36525. var serializedCondition = this._condition.serialize();
  36526. serializedCondition.children.push(serializationObject);
  36527. if (parent) {
  36528. parent.children.push(serializedCondition);
  36529. }
  36530. return serializedCondition;
  36531. }
  36532. if (parent) {
  36533. parent.children.push(serializationObject);
  36534. }
  36535. return serializationObject;
  36536. };
  36537. return Action;
  36538. }());
  36539. Action._SerializeValueAsString = function (value) {
  36540. if (typeof value === "number") {
  36541. return value.toString();
  36542. }
  36543. if (typeof value === "boolean") {
  36544. return value ? "true" : "false";
  36545. }
  36546. if (value instanceof BABYLON.Vector2) {
  36547. return value.x + ", " + value.y;
  36548. }
  36549. if (value instanceof BABYLON.Vector3) {
  36550. return value.x + ", " + value.y + ", " + value.z;
  36551. }
  36552. if (value instanceof BABYLON.Color3) {
  36553. return value.r + ", " + value.g + ", " + value.b;
  36554. }
  36555. if (value instanceof BABYLON.Color4) {
  36556. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  36557. }
  36558. return value; // string
  36559. };
  36560. Action._GetTargetProperty = function (target) {
  36561. return {
  36562. name: "target",
  36563. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  36564. : target instanceof BABYLON.Light ? "LightProperties"
  36565. : target instanceof BABYLON.Camera ? "CameraProperties"
  36566. : "SceneProperties",
  36567. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  36568. };
  36569. };
  36570. BABYLON.Action = Action;
  36571. })(BABYLON || (BABYLON = {}));
  36572. //# sourceMappingURL=babylon.action.js.map
  36573. var BABYLON;
  36574. (function (BABYLON) {
  36575. /**
  36576. * ActionEvent is the event beint sent when an action is triggered.
  36577. */
  36578. var ActionEvent = (function () {
  36579. /**
  36580. * @constructor
  36581. * @param source The mesh or sprite that triggered the action.
  36582. * @param pointerX The X mouse cursor position at the time of the event
  36583. * @param pointerY The Y mouse cursor position at the time of the event
  36584. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  36585. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  36586. */
  36587. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  36588. this.source = source;
  36589. this.pointerX = pointerX;
  36590. this.pointerY = pointerY;
  36591. this.meshUnderPointer = meshUnderPointer;
  36592. this.sourceEvent = sourceEvent;
  36593. this.additionalData = additionalData;
  36594. }
  36595. /**
  36596. * Helper function to auto-create an ActionEvent from a source mesh.
  36597. * @param source The source mesh that triggered the event
  36598. * @param evt {Event} The original (browser) event
  36599. */
  36600. ActionEvent.CreateNew = function (source, evt, additionalData) {
  36601. var scene = source.getScene();
  36602. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  36603. };
  36604. /**
  36605. * Helper function to auto-create an ActionEvent from a source mesh.
  36606. * @param source The source sprite that triggered the event
  36607. * @param scene Scene associated with the sprite
  36608. * @param evt {Event} The original (browser) event
  36609. */
  36610. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  36611. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  36612. };
  36613. /**
  36614. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  36615. * @param scene the scene where the event occurred
  36616. * @param evt {Event} The original (browser) event
  36617. */
  36618. ActionEvent.CreateNewFromScene = function (scene, evt) {
  36619. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  36620. };
  36621. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  36622. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  36623. };
  36624. return ActionEvent;
  36625. }());
  36626. BABYLON.ActionEvent = ActionEvent;
  36627. /**
  36628. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  36629. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  36630. */
  36631. var ActionManager = (function () {
  36632. function ActionManager(scene) {
  36633. // Members
  36634. this.actions = new Array();
  36635. this.hoverCursor = '';
  36636. this._scene = scene;
  36637. scene._actionManagers.push(this);
  36638. }
  36639. Object.defineProperty(ActionManager, "NothingTrigger", {
  36640. get: function () {
  36641. return ActionManager._NothingTrigger;
  36642. },
  36643. enumerable: true,
  36644. configurable: true
  36645. });
  36646. Object.defineProperty(ActionManager, "OnPickTrigger", {
  36647. get: function () {
  36648. return ActionManager._OnPickTrigger;
  36649. },
  36650. enumerable: true,
  36651. configurable: true
  36652. });
  36653. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  36654. get: function () {
  36655. return ActionManager._OnLeftPickTrigger;
  36656. },
  36657. enumerable: true,
  36658. configurable: true
  36659. });
  36660. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  36661. get: function () {
  36662. return ActionManager._OnRightPickTrigger;
  36663. },
  36664. enumerable: true,
  36665. configurable: true
  36666. });
  36667. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  36668. get: function () {
  36669. return ActionManager._OnCenterPickTrigger;
  36670. },
  36671. enumerable: true,
  36672. configurable: true
  36673. });
  36674. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  36675. get: function () {
  36676. return ActionManager._OnPickDownTrigger;
  36677. },
  36678. enumerable: true,
  36679. configurable: true
  36680. });
  36681. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  36682. get: function () {
  36683. return ActionManager._OnDoublePickTrigger;
  36684. },
  36685. enumerable: true,
  36686. configurable: true
  36687. });
  36688. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  36689. get: function () {
  36690. return ActionManager._OnPickUpTrigger;
  36691. },
  36692. enumerable: true,
  36693. configurable: true
  36694. });
  36695. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  36696. /// This trigger will only be raised if you also declared a OnPickDown
  36697. get: function () {
  36698. return ActionManager._OnPickOutTrigger;
  36699. },
  36700. enumerable: true,
  36701. configurable: true
  36702. });
  36703. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  36704. get: function () {
  36705. return ActionManager._OnLongPressTrigger;
  36706. },
  36707. enumerable: true,
  36708. configurable: true
  36709. });
  36710. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  36711. get: function () {
  36712. return ActionManager._OnPointerOverTrigger;
  36713. },
  36714. enumerable: true,
  36715. configurable: true
  36716. });
  36717. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  36718. get: function () {
  36719. return ActionManager._OnPointerOutTrigger;
  36720. },
  36721. enumerable: true,
  36722. configurable: true
  36723. });
  36724. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  36725. get: function () {
  36726. return ActionManager._OnEveryFrameTrigger;
  36727. },
  36728. enumerable: true,
  36729. configurable: true
  36730. });
  36731. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  36732. get: function () {
  36733. return ActionManager._OnIntersectionEnterTrigger;
  36734. },
  36735. enumerable: true,
  36736. configurable: true
  36737. });
  36738. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  36739. get: function () {
  36740. return ActionManager._OnIntersectionExitTrigger;
  36741. },
  36742. enumerable: true,
  36743. configurable: true
  36744. });
  36745. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  36746. get: function () {
  36747. return ActionManager._OnKeyDownTrigger;
  36748. },
  36749. enumerable: true,
  36750. configurable: true
  36751. });
  36752. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  36753. get: function () {
  36754. return ActionManager._OnKeyUpTrigger;
  36755. },
  36756. enumerable: true,
  36757. configurable: true
  36758. });
  36759. // Methods
  36760. ActionManager.prototype.dispose = function () {
  36761. var index = this._scene._actionManagers.indexOf(this);
  36762. for (var i = 0; i < this.actions.length; i++) {
  36763. var action = this.actions[i];
  36764. ActionManager.Triggers[action.trigger]--;
  36765. if (ActionManager.Triggers[action.trigger] === 0) {
  36766. delete ActionManager.Triggers[action.trigger];
  36767. }
  36768. }
  36769. if (index > -1) {
  36770. this._scene._actionManagers.splice(index, 1);
  36771. }
  36772. };
  36773. ActionManager.prototype.getScene = function () {
  36774. return this._scene;
  36775. };
  36776. /**
  36777. * Does this action manager handles actions of any of the given triggers
  36778. * @param {number[]} triggers - the triggers to be tested
  36779. * @return {boolean} whether one (or more) of the triggers is handeled
  36780. */
  36781. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  36782. for (var index = 0; index < this.actions.length; index++) {
  36783. var action = this.actions[index];
  36784. if (triggers.indexOf(action.trigger) > -1) {
  36785. return true;
  36786. }
  36787. }
  36788. return false;
  36789. };
  36790. /**
  36791. * Does this action manager handles actions of a given trigger
  36792. * @param {number} trigger - the trigger to be tested
  36793. * @return {boolean} whether the trigger is handeled
  36794. */
  36795. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  36796. for (var index = 0; index < this.actions.length; index++) {
  36797. var action = this.actions[index];
  36798. if (action.trigger === trigger) {
  36799. return true;
  36800. }
  36801. }
  36802. return false;
  36803. };
  36804. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  36805. /**
  36806. * Does this action manager has pointer triggers
  36807. * @return {boolean} whether or not it has pointer triggers
  36808. */
  36809. get: function () {
  36810. for (var index = 0; index < this.actions.length; index++) {
  36811. var action = this.actions[index];
  36812. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  36813. return true;
  36814. }
  36815. }
  36816. return false;
  36817. },
  36818. enumerable: true,
  36819. configurable: true
  36820. });
  36821. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  36822. /**
  36823. * Does this action manager has pick triggers
  36824. * @return {boolean} whether or not it has pick triggers
  36825. */
  36826. get: function () {
  36827. for (var index = 0; index < this.actions.length; index++) {
  36828. var action = this.actions[index];
  36829. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  36830. return true;
  36831. }
  36832. }
  36833. return false;
  36834. },
  36835. enumerable: true,
  36836. configurable: true
  36837. });
  36838. Object.defineProperty(ActionManager, "HasTriggers", {
  36839. /**
  36840. * Does exist one action manager with at least one trigger
  36841. * @return {boolean} whether or not it exists one action manager with one trigger
  36842. **/
  36843. get: function () {
  36844. for (var t in ActionManager.Triggers) {
  36845. if (ActionManager.Triggers.hasOwnProperty(t)) {
  36846. return true;
  36847. }
  36848. }
  36849. return false;
  36850. },
  36851. enumerable: true,
  36852. configurable: true
  36853. });
  36854. Object.defineProperty(ActionManager, "HasPickTriggers", {
  36855. /**
  36856. * Does exist one action manager with at least one pick trigger
  36857. * @return {boolean} whether or not it exists one action manager with one pick trigger
  36858. **/
  36859. get: function () {
  36860. for (var t in ActionManager.Triggers) {
  36861. if (ActionManager.Triggers.hasOwnProperty(t)) {
  36862. var t_int = parseInt(t);
  36863. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  36864. return true;
  36865. }
  36866. }
  36867. }
  36868. return false;
  36869. },
  36870. enumerable: true,
  36871. configurable: true
  36872. });
  36873. /**
  36874. * Does exist one action manager that handles actions of a given trigger
  36875. * @param {number} trigger - the trigger to be tested
  36876. * @return {boolean} whether the trigger is handeled by at least one action manager
  36877. **/
  36878. ActionManager.HasSpecificTrigger = function (trigger) {
  36879. for (var t in ActionManager.Triggers) {
  36880. if (ActionManager.Triggers.hasOwnProperty(t)) {
  36881. var t_int = parseInt(t);
  36882. if (t_int === trigger) {
  36883. return true;
  36884. }
  36885. }
  36886. }
  36887. return false;
  36888. };
  36889. /**
  36890. * Registers an action to this action manager
  36891. * @param {BABYLON.Action} action - the action to be registered
  36892. * @return {BABYLON.Action} the action amended (prepared) after registration
  36893. */
  36894. ActionManager.prototype.registerAction = function (action) {
  36895. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  36896. if (this.getScene().actionManager !== this) {
  36897. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  36898. return null;
  36899. }
  36900. }
  36901. this.actions.push(action);
  36902. if (ActionManager.Triggers[action.trigger]) {
  36903. ActionManager.Triggers[action.trigger]++;
  36904. }
  36905. else {
  36906. ActionManager.Triggers[action.trigger] = 1;
  36907. }
  36908. action._actionManager = this;
  36909. action._prepare();
  36910. return action;
  36911. };
  36912. /**
  36913. * Process a specific trigger
  36914. * @param {number} trigger - the trigger to process
  36915. * @param evt {BABYLON.ActionEvent} the event details to be processed
  36916. */
  36917. ActionManager.prototype.processTrigger = function (trigger, evt) {
  36918. for (var index = 0; index < this.actions.length; index++) {
  36919. var action = this.actions[index];
  36920. if (action.trigger === trigger) {
  36921. if (trigger === ActionManager.OnKeyUpTrigger
  36922. || trigger === ActionManager.OnKeyDownTrigger) {
  36923. var parameter = action.getTriggerParameter();
  36924. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  36925. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  36926. var actualkey = String.fromCharCode(unicode).toLowerCase();
  36927. if (actualkey !== parameter.toLowerCase()) {
  36928. continue;
  36929. }
  36930. }
  36931. }
  36932. action._executeCurrent(evt);
  36933. }
  36934. }
  36935. };
  36936. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  36937. var properties = propertyPath.split(".");
  36938. for (var index = 0; index < properties.length - 1; index++) {
  36939. target = target[properties[index]];
  36940. }
  36941. return target;
  36942. };
  36943. ActionManager.prototype._getProperty = function (propertyPath) {
  36944. var properties = propertyPath.split(".");
  36945. return properties[properties.length - 1];
  36946. };
  36947. ActionManager.prototype.serialize = function (name) {
  36948. var root = {
  36949. children: [],
  36950. name: name,
  36951. type: 3,
  36952. properties: [] // Empty for root but required
  36953. };
  36954. for (var i = 0; i < this.actions.length; i++) {
  36955. var triggerObject = {
  36956. type: 0,
  36957. children: [],
  36958. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  36959. properties: []
  36960. };
  36961. var triggerOptions = this.actions[i].triggerOptions;
  36962. if (triggerOptions && typeof triggerOptions !== "number") {
  36963. if (triggerOptions.parameter instanceof BABYLON.Node) {
  36964. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  36965. }
  36966. else {
  36967. var parameter = {};
  36968. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  36969. if (triggerOptions.parameter.mesh) {
  36970. parameter._meshId = triggerOptions.parameter.mesh.id;
  36971. }
  36972. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  36973. }
  36974. }
  36975. // Serialize child action, recursively
  36976. this.actions[i].serialize(triggerObject);
  36977. // Add serialized trigger
  36978. root.children.push(triggerObject);
  36979. }
  36980. return root;
  36981. };
  36982. ActionManager.Parse = function (parsedActions, object, scene) {
  36983. var actionManager = new BABYLON.ActionManager(scene);
  36984. if (object === null)
  36985. scene.actionManager = actionManager;
  36986. else
  36987. object.actionManager = actionManager;
  36988. // instanciate a new object
  36989. var instanciate = function (name, params) {
  36990. var newInstance = Object.create(BABYLON[name].prototype);
  36991. newInstance.constructor.apply(newInstance, params);
  36992. return newInstance;
  36993. };
  36994. var parseParameter = function (name, value, target, propertyPath) {
  36995. if (propertyPath === null) {
  36996. // String, boolean or float
  36997. var floatValue = parseFloat(value);
  36998. if (value === "true" || value === "false")
  36999. return value === "true";
  37000. else
  37001. return isNaN(floatValue) ? value : floatValue;
  37002. }
  37003. var effectiveTarget = propertyPath.split(".");
  37004. var values = value.split(",");
  37005. // Get effective Target
  37006. for (var i = 0; i < effectiveTarget.length; i++) {
  37007. target = target[effectiveTarget[i]];
  37008. }
  37009. // Return appropriate value with its type
  37010. if (typeof (target) === "boolean")
  37011. return values[0] === "true";
  37012. if (typeof (target) === "string")
  37013. return values[0];
  37014. // Parameters with multiple values such as Vector3 etc.
  37015. var split = new Array();
  37016. for (var i = 0; i < values.length; i++)
  37017. split.push(parseFloat(values[i]));
  37018. if (target instanceof BABYLON.Vector3)
  37019. return BABYLON.Vector3.FromArray(split);
  37020. if (target instanceof BABYLON.Vector4)
  37021. return BABYLON.Vector4.FromArray(split);
  37022. if (target instanceof BABYLON.Color3)
  37023. return BABYLON.Color3.FromArray(split);
  37024. if (target instanceof BABYLON.Color4)
  37025. return BABYLON.Color4.FromArray(split);
  37026. return parseFloat(values[0]);
  37027. };
  37028. // traverse graph per trigger
  37029. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  37030. if (combineArray === void 0) { combineArray = null; }
  37031. if (parsedAction.detached)
  37032. return;
  37033. var parameters = new Array();
  37034. var target = null;
  37035. var propertyPath = null;
  37036. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  37037. // Parameters
  37038. if (parsedAction.type === 2)
  37039. parameters.push(actionManager);
  37040. else
  37041. parameters.push(trigger);
  37042. if (combine) {
  37043. var actions = new Array();
  37044. for (var j = 0; j < parsedAction.combine.length; j++) {
  37045. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  37046. }
  37047. parameters.push(actions);
  37048. }
  37049. else {
  37050. for (var i = 0; i < parsedAction.properties.length; i++) {
  37051. var value = parsedAction.properties[i].value;
  37052. var name = parsedAction.properties[i].name;
  37053. var targetType = parsedAction.properties[i].targetType;
  37054. if (name === "target")
  37055. if (targetType !== null && targetType === "SceneProperties")
  37056. value = target = scene;
  37057. else
  37058. value = target = scene.getNodeByName(value);
  37059. else if (name === "parent")
  37060. value = scene.getNodeByName(value);
  37061. else if (name === "sound")
  37062. value = scene.getSoundByName(value);
  37063. else if (name !== "propertyPath") {
  37064. if (parsedAction.type === 2 && name === "operator")
  37065. value = BABYLON.ValueCondition[value];
  37066. else
  37067. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  37068. }
  37069. else {
  37070. propertyPath = value;
  37071. }
  37072. parameters.push(value);
  37073. }
  37074. }
  37075. if (combineArray === null) {
  37076. parameters.push(condition);
  37077. }
  37078. else {
  37079. parameters.push(null);
  37080. }
  37081. // If interpolate value action
  37082. if (parsedAction.name === "InterpolateValueAction") {
  37083. var param = parameters[parameters.length - 2];
  37084. parameters[parameters.length - 1] = param;
  37085. parameters[parameters.length - 2] = condition;
  37086. }
  37087. // Action or condition(s) and not CombineAction
  37088. var newAction = instanciate(parsedAction.name, parameters);
  37089. if (newAction instanceof BABYLON.Condition && condition !== null) {
  37090. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  37091. if (action)
  37092. action.then(nothing);
  37093. else
  37094. actionManager.registerAction(nothing);
  37095. action = nothing;
  37096. }
  37097. if (combineArray === null) {
  37098. if (newAction instanceof BABYLON.Condition) {
  37099. condition = newAction;
  37100. newAction = action;
  37101. }
  37102. else {
  37103. condition = null;
  37104. if (action)
  37105. action.then(newAction);
  37106. else
  37107. actionManager.registerAction(newAction);
  37108. }
  37109. }
  37110. else {
  37111. combineArray.push(newAction);
  37112. }
  37113. for (var i = 0; i < parsedAction.children.length; i++)
  37114. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  37115. };
  37116. // triggers
  37117. for (var i = 0; i < parsedActions.children.length; i++) {
  37118. var triggerParams;
  37119. var trigger = parsedActions.children[i];
  37120. if (trigger.properties.length > 0) {
  37121. var param = trigger.properties[0].value;
  37122. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  37123. if (value._meshId) {
  37124. value.mesh = scene.getMeshByID(value._meshId);
  37125. }
  37126. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  37127. }
  37128. else
  37129. triggerParams = BABYLON.ActionManager[trigger.name];
  37130. for (var j = 0; j < trigger.children.length; j++) {
  37131. if (!trigger.detached)
  37132. traverse(trigger.children[j], triggerParams, null, null);
  37133. }
  37134. }
  37135. };
  37136. ActionManager.GetTriggerName = function (trigger) {
  37137. switch (trigger) {
  37138. case 0: return "NothingTrigger";
  37139. case 1: return "OnPickTrigger";
  37140. case 2: return "OnLeftPickTrigger";
  37141. case 3: return "OnRightPickTrigger";
  37142. case 4: return "OnCenterPickTrigger";
  37143. case 5: return "OnPickDownTrigger";
  37144. case 6: return "OnPickUpTrigger";
  37145. case 7: return "OnLongPressTrigger";
  37146. case 8: return "OnPointerOverTrigger";
  37147. case 9: return "OnPointerOutTrigger";
  37148. case 10: return "OnEveryFrameTrigger";
  37149. case 11: return "OnIntersectionEnterTrigger";
  37150. case 12: return "OnIntersectionExitTrigger";
  37151. case 13: return "OnKeyDownTrigger";
  37152. case 14: return "OnKeyUpTrigger";
  37153. case 15: return "OnPickOutTrigger";
  37154. default: return "";
  37155. }
  37156. };
  37157. return ActionManager;
  37158. }());
  37159. // Statics
  37160. ActionManager._NothingTrigger = 0;
  37161. ActionManager._OnPickTrigger = 1;
  37162. ActionManager._OnLeftPickTrigger = 2;
  37163. ActionManager._OnRightPickTrigger = 3;
  37164. ActionManager._OnCenterPickTrigger = 4;
  37165. ActionManager._OnPickDownTrigger = 5;
  37166. ActionManager._OnDoublePickTrigger = 6;
  37167. ActionManager._OnPickUpTrigger = 7;
  37168. ActionManager._OnLongPressTrigger = 8;
  37169. ActionManager._OnPointerOverTrigger = 9;
  37170. ActionManager._OnPointerOutTrigger = 10;
  37171. ActionManager._OnEveryFrameTrigger = 11;
  37172. ActionManager._OnIntersectionEnterTrigger = 12;
  37173. ActionManager._OnIntersectionExitTrigger = 13;
  37174. ActionManager._OnKeyDownTrigger = 14;
  37175. ActionManager._OnKeyUpTrigger = 15;
  37176. ActionManager._OnPickOutTrigger = 16;
  37177. ActionManager.Triggers = {};
  37178. BABYLON.ActionManager = ActionManager;
  37179. })(BABYLON || (BABYLON = {}));
  37180. //# sourceMappingURL=babylon.actionManager.js.map
  37181. var BABYLON;
  37182. (function (BABYLON) {
  37183. var InterpolateValueAction = (function (_super) {
  37184. __extends(InterpolateValueAction, _super);
  37185. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  37186. if (duration === void 0) { duration = 1000; }
  37187. var _this = _super.call(this, triggerOptions, condition) || this;
  37188. _this.propertyPath = propertyPath;
  37189. _this.value = value;
  37190. _this.duration = duration;
  37191. _this.stopOtherAnimations = stopOtherAnimations;
  37192. _this.onInterpolationDone = onInterpolationDone;
  37193. _this._target = _this._effectiveTarget = target;
  37194. return _this;
  37195. }
  37196. InterpolateValueAction.prototype._prepare = function () {
  37197. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  37198. this._property = this._getProperty(this.propertyPath);
  37199. };
  37200. InterpolateValueAction.prototype.execute = function () {
  37201. var scene = this._actionManager.getScene();
  37202. var keys = [
  37203. {
  37204. frame: 0,
  37205. value: this._effectiveTarget[this._property]
  37206. }, {
  37207. frame: 100,
  37208. value: this.value
  37209. }
  37210. ];
  37211. var dataType;
  37212. if (typeof this.value === "number") {
  37213. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  37214. }
  37215. else if (this.value instanceof BABYLON.Color3) {
  37216. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  37217. }
  37218. else if (this.value instanceof BABYLON.Vector3) {
  37219. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  37220. }
  37221. else if (this.value instanceof BABYLON.Matrix) {
  37222. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  37223. }
  37224. else if (this.value instanceof BABYLON.Quaternion) {
  37225. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  37226. }
  37227. else {
  37228. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  37229. return;
  37230. }
  37231. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  37232. animation.setKeys(keys);
  37233. if (this.stopOtherAnimations) {
  37234. scene.stopAnimation(this._effectiveTarget);
  37235. }
  37236. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  37237. };
  37238. InterpolateValueAction.prototype.serialize = function (parent) {
  37239. return _super.prototype._serialize.call(this, {
  37240. name: "InterpolateValueAction",
  37241. properties: [
  37242. BABYLON.Action._GetTargetProperty(this._target),
  37243. { name: "propertyPath", value: this.propertyPath },
  37244. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  37245. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  37246. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  37247. ]
  37248. }, parent);
  37249. };
  37250. return InterpolateValueAction;
  37251. }(BABYLON.Action));
  37252. BABYLON.InterpolateValueAction = InterpolateValueAction;
  37253. })(BABYLON || (BABYLON = {}));
  37254. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  37255. var BABYLON;
  37256. (function (BABYLON) {
  37257. var SwitchBooleanAction = (function (_super) {
  37258. __extends(SwitchBooleanAction, _super);
  37259. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  37260. var _this = _super.call(this, triggerOptions, condition) || this;
  37261. _this.propertyPath = propertyPath;
  37262. _this._target = _this._effectiveTarget = target;
  37263. return _this;
  37264. }
  37265. SwitchBooleanAction.prototype._prepare = function () {
  37266. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  37267. this._property = this._getProperty(this.propertyPath);
  37268. };
  37269. SwitchBooleanAction.prototype.execute = function () {
  37270. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  37271. };
  37272. SwitchBooleanAction.prototype.serialize = function (parent) {
  37273. return _super.prototype._serialize.call(this, {
  37274. name: "SwitchBooleanAction",
  37275. properties: [
  37276. BABYLON.Action._GetTargetProperty(this._target),
  37277. { name: "propertyPath", value: this.propertyPath }
  37278. ]
  37279. }, parent);
  37280. };
  37281. return SwitchBooleanAction;
  37282. }(BABYLON.Action));
  37283. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  37284. var SetStateAction = (function (_super) {
  37285. __extends(SetStateAction, _super);
  37286. function SetStateAction(triggerOptions, target, value, condition) {
  37287. var _this = _super.call(this, triggerOptions, condition) || this;
  37288. _this.value = value;
  37289. _this._target = target;
  37290. return _this;
  37291. }
  37292. SetStateAction.prototype.execute = function () {
  37293. this._target.state = this.value;
  37294. };
  37295. SetStateAction.prototype.serialize = function (parent) {
  37296. return _super.prototype._serialize.call(this, {
  37297. name: "SetStateAction",
  37298. properties: [
  37299. BABYLON.Action._GetTargetProperty(this._target),
  37300. { name: "value", value: this.value }
  37301. ]
  37302. }, parent);
  37303. };
  37304. return SetStateAction;
  37305. }(BABYLON.Action));
  37306. BABYLON.SetStateAction = SetStateAction;
  37307. var SetValueAction = (function (_super) {
  37308. __extends(SetValueAction, _super);
  37309. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  37310. var _this = _super.call(this, triggerOptions, condition) || this;
  37311. _this.propertyPath = propertyPath;
  37312. _this.value = value;
  37313. _this._target = _this._effectiveTarget = target;
  37314. return _this;
  37315. }
  37316. SetValueAction.prototype._prepare = function () {
  37317. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  37318. this._property = this._getProperty(this.propertyPath);
  37319. };
  37320. SetValueAction.prototype.execute = function () {
  37321. this._effectiveTarget[this._property] = this.value;
  37322. if (this._target.markAsDirty) {
  37323. this._target.markAsDirty(this._property);
  37324. }
  37325. };
  37326. SetValueAction.prototype.serialize = function (parent) {
  37327. return _super.prototype._serialize.call(this, {
  37328. name: "SetValueAction",
  37329. properties: [
  37330. BABYLON.Action._GetTargetProperty(this._target),
  37331. { name: "propertyPath", value: this.propertyPath },
  37332. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  37333. ]
  37334. }, parent);
  37335. };
  37336. return SetValueAction;
  37337. }(BABYLON.Action));
  37338. BABYLON.SetValueAction = SetValueAction;
  37339. var IncrementValueAction = (function (_super) {
  37340. __extends(IncrementValueAction, _super);
  37341. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  37342. var _this = _super.call(this, triggerOptions, condition) || this;
  37343. _this.propertyPath = propertyPath;
  37344. _this.value = value;
  37345. _this._target = _this._effectiveTarget = target;
  37346. return _this;
  37347. }
  37348. IncrementValueAction.prototype._prepare = function () {
  37349. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  37350. this._property = this._getProperty(this.propertyPath);
  37351. if (typeof this._effectiveTarget[this._property] !== "number") {
  37352. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  37353. }
  37354. };
  37355. IncrementValueAction.prototype.execute = function () {
  37356. this._effectiveTarget[this._property] += this.value;
  37357. if (this._target.markAsDirty) {
  37358. this._target.markAsDirty(this._property);
  37359. }
  37360. };
  37361. IncrementValueAction.prototype.serialize = function (parent) {
  37362. return _super.prototype._serialize.call(this, {
  37363. name: "IncrementValueAction",
  37364. properties: [
  37365. BABYLON.Action._GetTargetProperty(this._target),
  37366. { name: "propertyPath", value: this.propertyPath },
  37367. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  37368. ]
  37369. }, parent);
  37370. };
  37371. return IncrementValueAction;
  37372. }(BABYLON.Action));
  37373. BABYLON.IncrementValueAction = IncrementValueAction;
  37374. var PlayAnimationAction = (function (_super) {
  37375. __extends(PlayAnimationAction, _super);
  37376. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  37377. var _this = _super.call(this, triggerOptions, condition) || this;
  37378. _this.from = from;
  37379. _this.to = to;
  37380. _this.loop = loop;
  37381. _this._target = target;
  37382. return _this;
  37383. }
  37384. PlayAnimationAction.prototype._prepare = function () {
  37385. };
  37386. PlayAnimationAction.prototype.execute = function () {
  37387. var scene = this._actionManager.getScene();
  37388. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  37389. };
  37390. PlayAnimationAction.prototype.serialize = function (parent) {
  37391. return _super.prototype._serialize.call(this, {
  37392. name: "PlayAnimationAction",
  37393. properties: [
  37394. BABYLON.Action._GetTargetProperty(this._target),
  37395. { name: "from", value: String(this.from) },
  37396. { name: "to", value: String(this.to) },
  37397. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  37398. ]
  37399. }, parent);
  37400. };
  37401. return PlayAnimationAction;
  37402. }(BABYLON.Action));
  37403. BABYLON.PlayAnimationAction = PlayAnimationAction;
  37404. var StopAnimationAction = (function (_super) {
  37405. __extends(StopAnimationAction, _super);
  37406. function StopAnimationAction(triggerOptions, target, condition) {
  37407. var _this = _super.call(this, triggerOptions, condition) || this;
  37408. _this._target = target;
  37409. return _this;
  37410. }
  37411. StopAnimationAction.prototype._prepare = function () {
  37412. };
  37413. StopAnimationAction.prototype.execute = function () {
  37414. var scene = this._actionManager.getScene();
  37415. scene.stopAnimation(this._target);
  37416. };
  37417. StopAnimationAction.prototype.serialize = function (parent) {
  37418. return _super.prototype._serialize.call(this, {
  37419. name: "StopAnimationAction",
  37420. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  37421. }, parent);
  37422. };
  37423. return StopAnimationAction;
  37424. }(BABYLON.Action));
  37425. BABYLON.StopAnimationAction = StopAnimationAction;
  37426. var DoNothingAction = (function (_super) {
  37427. __extends(DoNothingAction, _super);
  37428. function DoNothingAction(triggerOptions, condition) {
  37429. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  37430. return _super.call(this, triggerOptions, condition) || this;
  37431. }
  37432. DoNothingAction.prototype.execute = function () {
  37433. };
  37434. DoNothingAction.prototype.serialize = function (parent) {
  37435. return _super.prototype._serialize.call(this, {
  37436. name: "DoNothingAction",
  37437. properties: []
  37438. }, parent);
  37439. };
  37440. return DoNothingAction;
  37441. }(BABYLON.Action));
  37442. BABYLON.DoNothingAction = DoNothingAction;
  37443. var CombineAction = (function (_super) {
  37444. __extends(CombineAction, _super);
  37445. function CombineAction(triggerOptions, children, condition) {
  37446. var _this = _super.call(this, triggerOptions, condition) || this;
  37447. _this.children = children;
  37448. return _this;
  37449. }
  37450. CombineAction.prototype._prepare = function () {
  37451. for (var index = 0; index < this.children.length; index++) {
  37452. this.children[index]._actionManager = this._actionManager;
  37453. this.children[index]._prepare();
  37454. }
  37455. };
  37456. CombineAction.prototype.execute = function (evt) {
  37457. for (var index = 0; index < this.children.length; index++) {
  37458. this.children[index].execute(evt);
  37459. }
  37460. };
  37461. CombineAction.prototype.serialize = function (parent) {
  37462. var serializationObject = _super.prototype._serialize.call(this, {
  37463. name: "CombineAction",
  37464. properties: [],
  37465. combine: []
  37466. }, parent);
  37467. for (var i = 0; i < this.children.length; i++) {
  37468. serializationObject.combine.push(this.children[i].serialize(null));
  37469. }
  37470. return serializationObject;
  37471. };
  37472. return CombineAction;
  37473. }(BABYLON.Action));
  37474. BABYLON.CombineAction = CombineAction;
  37475. var ExecuteCodeAction = (function (_super) {
  37476. __extends(ExecuteCodeAction, _super);
  37477. function ExecuteCodeAction(triggerOptions, func, condition) {
  37478. var _this = _super.call(this, triggerOptions, condition) || this;
  37479. _this.func = func;
  37480. return _this;
  37481. }
  37482. ExecuteCodeAction.prototype.execute = function (evt) {
  37483. this.func(evt);
  37484. };
  37485. return ExecuteCodeAction;
  37486. }(BABYLON.Action));
  37487. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  37488. var SetParentAction = (function (_super) {
  37489. __extends(SetParentAction, _super);
  37490. function SetParentAction(triggerOptions, target, parent, condition) {
  37491. var _this = _super.call(this, triggerOptions, condition) || this;
  37492. _this._target = target;
  37493. _this._parent = parent;
  37494. return _this;
  37495. }
  37496. SetParentAction.prototype._prepare = function () {
  37497. };
  37498. SetParentAction.prototype.execute = function () {
  37499. if (this._target.parent === this._parent) {
  37500. return;
  37501. }
  37502. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  37503. invertParentWorldMatrix.invert();
  37504. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  37505. this._target.parent = this._parent;
  37506. };
  37507. SetParentAction.prototype.serialize = function (parent) {
  37508. return _super.prototype._serialize.call(this, {
  37509. name: "SetParentAction",
  37510. properties: [
  37511. BABYLON.Action._GetTargetProperty(this._target),
  37512. BABYLON.Action._GetTargetProperty(this._parent),
  37513. ]
  37514. }, parent);
  37515. };
  37516. return SetParentAction;
  37517. }(BABYLON.Action));
  37518. BABYLON.SetParentAction = SetParentAction;
  37519. var PlaySoundAction = (function (_super) {
  37520. __extends(PlaySoundAction, _super);
  37521. function PlaySoundAction(triggerOptions, sound, condition) {
  37522. var _this = _super.call(this, triggerOptions, condition) || this;
  37523. _this._sound = sound;
  37524. return _this;
  37525. }
  37526. PlaySoundAction.prototype._prepare = function () {
  37527. };
  37528. PlaySoundAction.prototype.execute = function () {
  37529. if (this._sound !== undefined)
  37530. this._sound.play();
  37531. };
  37532. PlaySoundAction.prototype.serialize = function (parent) {
  37533. return _super.prototype._serialize.call(this, {
  37534. name: "PlaySoundAction",
  37535. properties: [{ name: "sound", value: this._sound.name }]
  37536. }, parent);
  37537. };
  37538. return PlaySoundAction;
  37539. }(BABYLON.Action));
  37540. BABYLON.PlaySoundAction = PlaySoundAction;
  37541. var StopSoundAction = (function (_super) {
  37542. __extends(StopSoundAction, _super);
  37543. function StopSoundAction(triggerOptions, sound, condition) {
  37544. var _this = _super.call(this, triggerOptions, condition) || this;
  37545. _this._sound = sound;
  37546. return _this;
  37547. }
  37548. StopSoundAction.prototype._prepare = function () {
  37549. };
  37550. StopSoundAction.prototype.execute = function () {
  37551. if (this._sound !== undefined)
  37552. this._sound.stop();
  37553. };
  37554. StopSoundAction.prototype.serialize = function (parent) {
  37555. return _super.prototype._serialize.call(this, {
  37556. name: "StopSoundAction",
  37557. properties: [{ name: "sound", value: this._sound.name }]
  37558. }, parent);
  37559. };
  37560. return StopSoundAction;
  37561. }(BABYLON.Action));
  37562. BABYLON.StopSoundAction = StopSoundAction;
  37563. })(BABYLON || (BABYLON = {}));
  37564. //# sourceMappingURL=babylon.directActions.js.map
  37565. var BABYLON;
  37566. (function (BABYLON) {
  37567. var Debug;
  37568. (function (Debug) {
  37569. /**
  37570. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  37571. */
  37572. var SkeletonViewer = (function () {
  37573. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  37574. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  37575. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  37576. this.skeleton = skeleton;
  37577. this.mesh = mesh;
  37578. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  37579. this.renderingGroupId = renderingGroupId;
  37580. this.color = BABYLON.Color3.White();
  37581. this._debugLines = [];
  37582. this._isEnabled = false;
  37583. this._scene = scene;
  37584. this.update();
  37585. this._renderFunction = this.update.bind(this);
  37586. }
  37587. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  37588. get: function () {
  37589. return this._isEnabled;
  37590. },
  37591. set: function (value) {
  37592. if (this._isEnabled === value) {
  37593. return;
  37594. }
  37595. this._isEnabled = value;
  37596. if (value) {
  37597. this._scene.registerBeforeRender(this._renderFunction);
  37598. }
  37599. else {
  37600. this._scene.unregisterBeforeRender(this._renderFunction);
  37601. }
  37602. },
  37603. enumerable: true,
  37604. configurable: true
  37605. });
  37606. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  37607. if (x === void 0) { x = 0; }
  37608. if (y === void 0) { y = 0; }
  37609. if (z === void 0) { z = 0; }
  37610. var tmat = BABYLON.Tmp.Matrix[0];
  37611. var parentBone = bone.getParent();
  37612. tmat.copyFrom(bone.getLocalMatrix());
  37613. if (x !== 0 || y !== 0 || z !== 0) {
  37614. var tmat2 = BABYLON.Tmp.Matrix[1];
  37615. BABYLON.Matrix.IdentityToRef(tmat2);
  37616. tmat2.m[12] = x;
  37617. tmat2.m[13] = y;
  37618. tmat2.m[14] = z;
  37619. tmat2.multiplyToRef(tmat, tmat);
  37620. }
  37621. if (parentBone) {
  37622. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  37623. }
  37624. tmat.multiplyToRef(meshMat, tmat);
  37625. position.x = tmat.m[12];
  37626. position.y = tmat.m[13];
  37627. position.z = tmat.m[14];
  37628. };
  37629. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  37630. var len = bones.length;
  37631. var meshPos = this.mesh.position;
  37632. for (var i = 0; i < len; i++) {
  37633. var bone = bones[i];
  37634. var points = this._debugLines[i];
  37635. if (!points) {
  37636. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  37637. this._debugLines[i] = points;
  37638. }
  37639. this._getBonePosition(points[0], bone, meshMat);
  37640. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  37641. points[0].subtractInPlace(meshPos);
  37642. points[1].subtractInPlace(meshPos);
  37643. }
  37644. };
  37645. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  37646. var len = bones.length;
  37647. var boneNum = 0;
  37648. var meshPos = this.mesh.position;
  37649. for (var i = len - 1; i >= 0; i--) {
  37650. var childBone = bones[i];
  37651. var parentBone = childBone.getParent();
  37652. if (!parentBone) {
  37653. continue;
  37654. }
  37655. var points = this._debugLines[boneNum];
  37656. if (!points) {
  37657. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  37658. this._debugLines[boneNum] = points;
  37659. }
  37660. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  37661. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  37662. points[0].subtractInPlace(meshPos);
  37663. points[1].subtractInPlace(meshPos);
  37664. boneNum++;
  37665. }
  37666. };
  37667. SkeletonViewer.prototype.update = function () {
  37668. if (this.autoUpdateBonesMatrices) {
  37669. this.skeleton.computeAbsoluteTransforms();
  37670. }
  37671. if (this.skeleton.bones[0].length === undefined) {
  37672. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  37673. }
  37674. else {
  37675. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  37676. }
  37677. if (!this._debugMesh) {
  37678. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  37679. this._debugMesh.renderingGroupId = this.renderingGroupId;
  37680. }
  37681. else {
  37682. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  37683. }
  37684. this._debugMesh.position.copyFrom(this.mesh.position);
  37685. this._debugMesh.color = this.color;
  37686. };
  37687. SkeletonViewer.prototype.dispose = function () {
  37688. if (this._debugMesh) {
  37689. this.isEnabled = false;
  37690. this._debugMesh.dispose();
  37691. this._debugMesh = null;
  37692. }
  37693. };
  37694. return SkeletonViewer;
  37695. }());
  37696. Debug.SkeletonViewer = SkeletonViewer;
  37697. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  37698. })(BABYLON || (BABYLON = {}));
  37699. //# sourceMappingURL=babylon.skeletonViewer.js.map
  37700. var BABYLON;
  37701. (function (BABYLON) {
  37702. var Debug;
  37703. (function (Debug) {
  37704. var AxesViewer = (function () {
  37705. function AxesViewer(scene, scaleLines) {
  37706. if (scaleLines === void 0) { scaleLines = 1; }
  37707. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  37708. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  37709. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  37710. this.scaleLines = 1;
  37711. this.scaleLines = scaleLines;
  37712. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  37713. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  37714. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  37715. this._xmesh.renderingGroupId = 2;
  37716. this._ymesh.renderingGroupId = 2;
  37717. this._zmesh.renderingGroupId = 2;
  37718. this._xmesh.material.checkReadyOnlyOnce = true;
  37719. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  37720. this._ymesh.material.checkReadyOnlyOnce = true;
  37721. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  37722. this._zmesh.material.checkReadyOnlyOnce = true;
  37723. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  37724. this.scene = scene;
  37725. }
  37726. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  37727. var scaleLines = this.scaleLines;
  37728. this._xmesh.position.copyFrom(position);
  37729. this._ymesh.position.copyFrom(position);
  37730. this._zmesh.position.copyFrom(position);
  37731. var point2 = this._xline[1];
  37732. point2.x = xaxis.x * scaleLines;
  37733. point2.y = xaxis.y * scaleLines;
  37734. point2.z = xaxis.z * scaleLines;
  37735. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  37736. point2 = this._yline[1];
  37737. point2.x = yaxis.x * scaleLines;
  37738. point2.y = yaxis.y * scaleLines;
  37739. point2.z = yaxis.z * scaleLines;
  37740. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  37741. point2 = this._zline[1];
  37742. point2.x = zaxis.x * scaleLines;
  37743. point2.y = zaxis.y * scaleLines;
  37744. point2.z = zaxis.z * scaleLines;
  37745. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  37746. };
  37747. AxesViewer.prototype.dispose = function () {
  37748. if (this._xmesh) {
  37749. this._xmesh.dispose();
  37750. this._ymesh.dispose();
  37751. this._zmesh.dispose();
  37752. this._xmesh = null;
  37753. this._ymesh = null;
  37754. this._zmesh = null;
  37755. this._xline = null;
  37756. this._yline = null;
  37757. this._zline = null;
  37758. this.scene = null;
  37759. }
  37760. };
  37761. return AxesViewer;
  37762. }());
  37763. Debug.AxesViewer = AxesViewer;
  37764. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  37765. })(BABYLON || (BABYLON = {}));
  37766. //# sourceMappingURL=babylon.axesViewer.js.map
  37767. var BABYLON;
  37768. (function (BABYLON) {
  37769. var Debug;
  37770. (function (Debug) {
  37771. var BoneAxesViewer = (function (_super) {
  37772. __extends(BoneAxesViewer, _super);
  37773. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  37774. if (scaleLines === void 0) { scaleLines = 1; }
  37775. var _this = _super.call(this, scene, scaleLines) || this;
  37776. _this.pos = BABYLON.Vector3.Zero();
  37777. _this.xaxis = BABYLON.Vector3.Zero();
  37778. _this.yaxis = BABYLON.Vector3.Zero();
  37779. _this.zaxis = BABYLON.Vector3.Zero();
  37780. _this.mesh = mesh;
  37781. _this.bone = bone;
  37782. return _this;
  37783. }
  37784. BoneAxesViewer.prototype.update = function () {
  37785. var bone = this.bone;
  37786. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  37787. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  37788. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  37789. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  37790. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  37791. };
  37792. BoneAxesViewer.prototype.dispose = function () {
  37793. if (this.pos) {
  37794. this.pos = null;
  37795. this.xaxis = null;
  37796. this.yaxis = null;
  37797. this.zaxis = null;
  37798. this.mesh = null;
  37799. this.bone = null;
  37800. _super.prototype.dispose.call(this);
  37801. }
  37802. };
  37803. return BoneAxesViewer;
  37804. }(Debug.AxesViewer));
  37805. Debug.BoneAxesViewer = BoneAxesViewer;
  37806. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  37807. })(BABYLON || (BABYLON = {}));
  37808. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  37809. var BABYLON;
  37810. (function (BABYLON) {
  37811. var RayHelper = (function () {
  37812. function RayHelper(ray) {
  37813. this.ray = ray;
  37814. }
  37815. RayHelper.CreateAndShow = function (ray, scene, color) {
  37816. var helper = new RayHelper(ray);
  37817. helper.show(scene, color);
  37818. return helper;
  37819. };
  37820. RayHelper.prototype.show = function (scene, color) {
  37821. if (!this._renderFunction) {
  37822. var ray = this.ray;
  37823. this._renderFunction = this._render.bind(this);
  37824. this._scene = scene;
  37825. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  37826. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  37827. this._scene.registerBeforeRender(this._renderFunction);
  37828. }
  37829. if (color) {
  37830. this._renderLine.color.copyFrom(color);
  37831. }
  37832. };
  37833. RayHelper.prototype.hide = function () {
  37834. if (this._renderFunction) {
  37835. this._scene.unregisterBeforeRender(this._renderFunction);
  37836. this._scene = null;
  37837. this._renderFunction = null;
  37838. this._renderLine.dispose();
  37839. this._renderLine = null;
  37840. this._renderPoints = null;
  37841. }
  37842. };
  37843. RayHelper.prototype._render = function () {
  37844. var ray = this.ray;
  37845. var point = this._renderPoints[1];
  37846. var len = Math.min(ray.length, 1000000);
  37847. point.copyFrom(ray.direction);
  37848. point.scaleInPlace(len);
  37849. point.addInPlace(ray.origin);
  37850. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  37851. };
  37852. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  37853. this._attachedToMesh = mesh;
  37854. var ray = this.ray;
  37855. if (!ray.direction) {
  37856. ray.direction = BABYLON.Vector3.Zero();
  37857. }
  37858. if (!ray.origin) {
  37859. ray.origin = BABYLON.Vector3.Zero();
  37860. }
  37861. if (length) {
  37862. ray.length = length;
  37863. }
  37864. if (!meshSpaceOrigin) {
  37865. meshSpaceOrigin = BABYLON.Vector3.Zero();
  37866. }
  37867. if (!meshSpaceDirection) {
  37868. // -1 so that this will work with Mesh.lookAt
  37869. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  37870. }
  37871. if (!this._meshSpaceDirection) {
  37872. this._meshSpaceDirection = meshSpaceDirection.clone();
  37873. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  37874. }
  37875. else {
  37876. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  37877. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  37878. }
  37879. if (!this._updateToMeshFunction) {
  37880. this._updateToMeshFunction = this._updateToMesh.bind(this);
  37881. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  37882. }
  37883. this._updateToMesh();
  37884. };
  37885. RayHelper.prototype.detachFromMesh = function () {
  37886. if (this._attachedToMesh) {
  37887. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  37888. this._attachedToMesh = null;
  37889. this._updateToMeshFunction = null;
  37890. }
  37891. };
  37892. RayHelper.prototype._updateToMesh = function () {
  37893. var ray = this.ray;
  37894. if (this._attachedToMesh._isDisposed) {
  37895. this.detachFromMesh();
  37896. return;
  37897. }
  37898. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  37899. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  37900. };
  37901. RayHelper.prototype.dispose = function () {
  37902. this.hide();
  37903. this.detachFromMesh();
  37904. this.ray = null;
  37905. };
  37906. return RayHelper;
  37907. }());
  37908. BABYLON.RayHelper = RayHelper;
  37909. })(BABYLON || (BABYLON = {}));
  37910. //# sourceMappingURL=babylon.rayHelper.js.map
  37911. var BABYLON;
  37912. (function (BABYLON) {
  37913. var DebugLayer = (function () {
  37914. function DebugLayer(scene) {
  37915. this._scene = scene;
  37916. }
  37917. /** Creates the inspector window. */
  37918. DebugLayer.prototype._createInspector = function (config) {
  37919. if (config === void 0) { config = {}; }
  37920. var popup = config.popup || false;
  37921. var initialTab = config.initialTab || 0;
  37922. var parentElement = config.parentElement || null;
  37923. if (!this._inspector) {
  37924. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  37925. } // else nothing to do,; instance is already existing
  37926. };
  37927. DebugLayer.prototype.isVisible = function () {
  37928. if (!this._inspector) {
  37929. return false;
  37930. }
  37931. return true;
  37932. };
  37933. DebugLayer.prototype.hide = function () {
  37934. if (this._inspector) {
  37935. try {
  37936. this._inspector.dispose();
  37937. }
  37938. catch (e) {
  37939. // If the inspector has been removed directly from the inspector tool
  37940. }
  37941. this._inspector = null;
  37942. }
  37943. };
  37944. DebugLayer.prototype.show = function (config) {
  37945. if (config === void 0) { config = {}; }
  37946. if (typeof INSPECTOR == 'undefined') {
  37947. // Load inspector and add it to the DOM
  37948. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  37949. }
  37950. else {
  37951. // Otherwise creates the inspector
  37952. this._createInspector(config);
  37953. }
  37954. };
  37955. return DebugLayer;
  37956. }());
  37957. // Get protocol used - http or https
  37958. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//www.babylonjs.com/babylon.inspector.bundle.js';
  37959. BABYLON.DebugLayer = DebugLayer;
  37960. })(BABYLON || (BABYLON = {}));
  37961. //# sourceMappingURL=babylon.debugLayer.js.map
  37962. var BABYLON;
  37963. (function (BABYLON) {
  37964. var BoundingBoxRenderer = (function () {
  37965. function BoundingBoxRenderer(scene) {
  37966. this.frontColor = new BABYLON.Color3(1, 1, 1);
  37967. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  37968. this.showBackLines = true;
  37969. this.renderList = new BABYLON.SmartArray(32);
  37970. this._vertexBuffers = {};
  37971. this._scene = scene;
  37972. }
  37973. BoundingBoxRenderer.prototype._prepareRessources = function () {
  37974. if (this._colorShader) {
  37975. return;
  37976. }
  37977. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  37978. attributes: [BABYLON.VertexBuffer.PositionKind],
  37979. uniforms: ["world", "viewProjection", "color"]
  37980. });
  37981. var engine = this._scene.getEngine();
  37982. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  37983. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  37984. 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]);
  37985. };
  37986. BoundingBoxRenderer.prototype.reset = function () {
  37987. this.renderList.reset();
  37988. };
  37989. BoundingBoxRenderer.prototype.render = function () {
  37990. if (this.renderList.length === 0) {
  37991. return;
  37992. }
  37993. this._prepareRessources();
  37994. if (!this._colorShader.isReady()) {
  37995. return;
  37996. }
  37997. var engine = this._scene.getEngine();
  37998. engine.setDepthWrite(false);
  37999. this._colorShader._preBind();
  38000. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  38001. var boundingBox = this.renderList.data[boundingBoxIndex];
  38002. var min = boundingBox.minimum;
  38003. var max = boundingBox.maximum;
  38004. var diff = max.subtract(min);
  38005. var median = min.add(diff.scale(0.5));
  38006. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  38007. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  38008. .multiply(boundingBox.getWorldMatrix());
  38009. // VBOs
  38010. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  38011. if (this.showBackLines) {
  38012. // Back
  38013. engine.setDepthFunctionToGreaterOrEqual();
  38014. this._scene.resetCachedMaterial();
  38015. this._colorShader.setColor4("color", this.backColor.toColor4());
  38016. this._colorShader.bind(worldMatrix);
  38017. // Draw order
  38018. engine.draw(false, 0, 24);
  38019. }
  38020. // Front
  38021. engine.setDepthFunctionToLess();
  38022. this._scene.resetCachedMaterial();
  38023. this._colorShader.setColor4("color", this.frontColor.toColor4());
  38024. this._colorShader.bind(worldMatrix);
  38025. // Draw order
  38026. engine.draw(false, 0, 24);
  38027. }
  38028. this._colorShader.unbind();
  38029. engine.setDepthFunctionToLessOrEqual();
  38030. engine.setDepthWrite(true);
  38031. };
  38032. BoundingBoxRenderer.prototype.dispose = function () {
  38033. if (!this._colorShader) {
  38034. return;
  38035. }
  38036. this.renderList.dispose();
  38037. this._colorShader.dispose();
  38038. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  38039. if (buffer) {
  38040. buffer.dispose();
  38041. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  38042. }
  38043. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  38044. };
  38045. return BoundingBoxRenderer;
  38046. }());
  38047. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  38048. })(BABYLON || (BABYLON = {}));
  38049. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  38050. var BABYLON;
  38051. (function (BABYLON) {
  38052. var MultiMaterial = (function (_super) {
  38053. __extends(MultiMaterial, _super);
  38054. function MultiMaterial(name, scene) {
  38055. var _this = _super.call(this, name, scene, true) || this;
  38056. _this.subMaterials = new Array();
  38057. scene.multiMaterials.push(_this);
  38058. return _this;
  38059. }
  38060. // Properties
  38061. MultiMaterial.prototype.getSubMaterial = function (index) {
  38062. if (index < 0 || index >= this.subMaterials.length) {
  38063. return this.getScene().defaultMaterial;
  38064. }
  38065. return this.subMaterials[index];
  38066. };
  38067. // Methods
  38068. MultiMaterial.prototype.getClassName = function () {
  38069. return "MultiMaterial";
  38070. };
  38071. MultiMaterial.prototype.isReady = function (mesh) {
  38072. for (var index = 0; index < this.subMaterials.length; index++) {
  38073. var subMaterial = this.subMaterials[index];
  38074. if (subMaterial) {
  38075. if (!this.subMaterials[index].isReady(mesh)) {
  38076. return false;
  38077. }
  38078. }
  38079. }
  38080. return true;
  38081. };
  38082. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  38083. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  38084. for (var index = 0; index < this.subMaterials.length; index++) {
  38085. var subMaterial = null;
  38086. if (cloneChildren) {
  38087. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  38088. }
  38089. else {
  38090. subMaterial = this.subMaterials[index];
  38091. }
  38092. newMultiMaterial.subMaterials.push(subMaterial);
  38093. }
  38094. return newMultiMaterial;
  38095. };
  38096. MultiMaterial.prototype.serialize = function () {
  38097. var serializationObject = {};
  38098. serializationObject.name = this.name;
  38099. serializationObject.id = this.id;
  38100. serializationObject.tags = BABYLON.Tags.GetTags(this);
  38101. serializationObject.materials = [];
  38102. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  38103. var subMat = this.subMaterials[matIndex];
  38104. if (subMat) {
  38105. serializationObject.materials.push(subMat.id);
  38106. }
  38107. else {
  38108. serializationObject.materials.push(null);
  38109. }
  38110. }
  38111. return serializationObject;
  38112. };
  38113. return MultiMaterial;
  38114. }(BABYLON.Material));
  38115. BABYLON.MultiMaterial = MultiMaterial;
  38116. })(BABYLON || (BABYLON = {}));
  38117. //# sourceMappingURL=babylon.multiMaterial.js.map
  38118. var BABYLON;
  38119. (function (BABYLON) {
  38120. var PBRMaterialDefines = (function (_super) {
  38121. __extends(PBRMaterialDefines, _super);
  38122. function PBRMaterialDefines() {
  38123. var _this = _super.call(this) || this;
  38124. _this.PBR = true;
  38125. _this.ALBEDO = false;
  38126. _this.AMBIENT = false;
  38127. _this.AMBIENTINGRAYSCALE = false;
  38128. _this.OPACITY = false;
  38129. _this.OPACITYRGB = false;
  38130. _this.REFLECTION = false;
  38131. _this.EMISSIVE = false;
  38132. _this.REFLECTIVITY = false;
  38133. _this.BUMP = false;
  38134. _this.PARALLAX = false;
  38135. _this.PARALLAXOCCLUSION = false;
  38136. _this.SPECULAROVERALPHA = false;
  38137. _this.CLIPPLANE = false;
  38138. _this.ALPHATEST = false;
  38139. _this.ALPHAFROMALBEDO = false;
  38140. _this.POINTSIZE = false;
  38141. _this.FOG = false;
  38142. _this.SPECULARTERM = false;
  38143. _this.OPACITYFRESNEL = false;
  38144. _this.EMISSIVEFRESNEL = false;
  38145. _this.FRESNEL = false;
  38146. _this.NORMAL = false;
  38147. _this.TANGENT = false;
  38148. _this.UV1 = false;
  38149. _this.UV2 = false;
  38150. _this.VERTEXCOLOR = false;
  38151. _this.VERTEXALPHA = false;
  38152. _this.NUM_BONE_INFLUENCERS = 0;
  38153. _this.BonesPerMesh = 0;
  38154. _this.INSTANCES = false;
  38155. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  38156. _this.MICROSURFACEAUTOMATIC = false;
  38157. _this.EMISSIVEASILLUMINATION = false;
  38158. _this.LIGHTMAP = false;
  38159. _this.USELIGHTMAPASSHADOWMAP = false;
  38160. _this.REFLECTIONMAP_3D = false;
  38161. _this.REFLECTIONMAP_SPHERICAL = false;
  38162. _this.REFLECTIONMAP_PLANAR = false;
  38163. _this.REFLECTIONMAP_CUBIC = false;
  38164. _this.REFLECTIONMAP_PROJECTION = false;
  38165. _this.REFLECTIONMAP_SKYBOX = false;
  38166. _this.REFLECTIONMAP_EXPLICIT = false;
  38167. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38168. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38169. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38170. _this.INVERTCUBICMAP = false;
  38171. _this.LOGARITHMICDEPTH = false;
  38172. _this.CAMERATONEMAP = false;
  38173. _this.CAMERACONTRAST = false;
  38174. _this.CAMERACOLORGRADING = false;
  38175. _this.CAMERACOLORCURVES = false;
  38176. _this.USESPHERICALFROMREFLECTIONMAP = false;
  38177. _this.REFRACTION = false;
  38178. _this.REFRACTIONMAP_3D = false;
  38179. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  38180. _this.REFRACTIONMAPINLINEARSPACE = false;
  38181. _this.LODBASEDMICROSFURACE = false;
  38182. _this.USEPHYSICALLIGHTFALLOFF = false;
  38183. _this.RADIANCEOVERALPHA = false;
  38184. _this.USEPMREMREFLECTION = false;
  38185. _this.USEPMREMREFRACTION = false;
  38186. _this.INVERTNORMALMAPX = false;
  38187. _this.INVERTNORMALMAPY = false;
  38188. _this.TWOSIDEDLIGHTING = false;
  38189. _this.SHADOWFULLFLOAT = false;
  38190. _this.NORMALXYSCALE = true;
  38191. _this.USERIGHTHANDEDSYSTEM = false;
  38192. _this.METALLICWORKFLOW = false;
  38193. _this.METALLICMAP = false;
  38194. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  38195. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  38196. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  38197. _this.AOSTOREINMETALMAPRED = false;
  38198. _this.MICROSURFACEMAP = false;
  38199. _this.MORPHTARGETS = false;
  38200. _this.MORPHTARGETS_NORMAL = false;
  38201. _this.MORPHTARGETS_TANGENT = false;
  38202. _this.NUM_MORPH_INFLUENCERS = 0;
  38203. _this.ALPHATESTVALUE = 0.4;
  38204. _this.LDROUTPUT = true;
  38205. _this.rebuild();
  38206. return _this;
  38207. }
  38208. PBRMaterialDefines.prototype.reset = function () {
  38209. _super.prototype.reset.call(this);
  38210. this.ALPHATESTVALUE = 0.4;
  38211. this.PBR = true;
  38212. };
  38213. return PBRMaterialDefines;
  38214. }(BABYLON.MaterialDefines));
  38215. /**
  38216. * The Physically based material base class of BJS.
  38217. *
  38218. * This offers the main features of a standard PBR material.
  38219. * For more information, please refer to the documentation :
  38220. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  38221. */
  38222. var PBRBaseMaterial = (function (_super) {
  38223. __extends(PBRBaseMaterial, _super);
  38224. /**
  38225. * Instantiates a new PBRMaterial instance.
  38226. *
  38227. * @param name The material name
  38228. * @param scene The scene the material will be use in.
  38229. */
  38230. function PBRBaseMaterial(name, scene) {
  38231. var _this = _super.call(this, name, scene) || this;
  38232. /**
  38233. * Intensity of the direct lights e.g. the four lights available in your scene.
  38234. * This impacts both the direct diffuse and specular highlights.
  38235. */
  38236. _this._directIntensity = 1.0;
  38237. /**
  38238. * Intensity of the emissive part of the material.
  38239. * This helps controlling the emissive effect without modifying the emissive color.
  38240. */
  38241. _this._emissiveIntensity = 1.0;
  38242. /**
  38243. * Intensity of the environment e.g. how much the environment will light the object
  38244. * either through harmonics for rough material or through the refelction for shiny ones.
  38245. */
  38246. _this._environmentIntensity = 1.0;
  38247. /**
  38248. * This is a special control allowing the reduction of the specular highlights coming from the
  38249. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  38250. */
  38251. _this._specularIntensity = 1.0;
  38252. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  38253. /**
  38254. * Debug Control allowing disabling the bump map on this material.
  38255. */
  38256. _this._disableBumpMap = false;
  38257. /**
  38258. * The camera exposure used on this material.
  38259. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38260. * This corresponds to a photographic exposure.
  38261. */
  38262. _this._cameraExposure = 1.0;
  38263. /**
  38264. * The camera contrast used on this material.
  38265. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  38266. */
  38267. _this._cameraContrast = 1.0;
  38268. /**
  38269. * Color Grading 2D Lookup Texture.
  38270. * This allows special effects like sepia, black and white to sixties rendering style.
  38271. */
  38272. _this._cameraColorGradingTexture = null;
  38273. /**
  38274. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38275. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38276. * 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;
  38277. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38278. */
  38279. _this._cameraColorCurves = null;
  38280. _this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  38281. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  38282. /**
  38283. * AKA Occlusion Texture Intensity in other nomenclature.
  38284. */
  38285. _this._ambientTextureStrength = 1.0;
  38286. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  38287. /**
  38288. * AKA Diffuse Color in other nomenclature.
  38289. */
  38290. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  38291. /**
  38292. * AKA Specular Color in other nomenclature.
  38293. */
  38294. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  38295. _this._reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  38296. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  38297. /**
  38298. * AKA Glossiness in other nomenclature.
  38299. */
  38300. _this._microSurface = 0.9;
  38301. /**
  38302. * source material index of refraction (IOR)' / 'destination material IOR.
  38303. */
  38304. _this._indexOfRefraction = 0.66;
  38305. /**
  38306. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  38307. */
  38308. _this._invertRefractionY = false;
  38309. /**
  38310. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  38311. * Materials half opaque for instance using refraction could benefit from this control.
  38312. */
  38313. _this._linkRefractionWithTransparency = false;
  38314. _this._useLightmapAsShadowmap = false;
  38315. /**
  38316. * In this mode, the emissive informtaion will always be added to the lighting once.
  38317. * A light for instance can be thought as emissive.
  38318. */
  38319. _this._useEmissiveAsIllumination = false;
  38320. /**
  38321. * Secifies that the alpha is coming form the albedo channel alpha channel.
  38322. */
  38323. _this._useAlphaFromAlbedoTexture = false;
  38324. /**
  38325. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  38326. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  38327. */
  38328. _this._useSpecularOverAlpha = true;
  38329. /**
  38330. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  38331. */
  38332. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  38333. /**
  38334. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  38335. */
  38336. _this._useRoughnessFromMetallicTextureAlpha = true;
  38337. /**
  38338. * Specifies if the metallic texture contains the roughness information in its green channel.
  38339. */
  38340. _this._useRoughnessFromMetallicTextureGreen = false;
  38341. /**
  38342. * Specifies if the metallic texture contains the metallness information in its blue channel.
  38343. */
  38344. _this._useMetallnessFromMetallicTextureBlue = false;
  38345. /**
  38346. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  38347. */
  38348. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  38349. /**
  38350. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  38351. */
  38352. _this._useAmbientInGrayScale = false;
  38353. /**
  38354. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  38355. * The material will try to infer what glossiness each pixel should be.
  38356. */
  38357. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  38358. /**
  38359. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  38360. * the creation of the material.
  38361. */
  38362. _this._useScalarInLinearSpace = false;
  38363. /**
  38364. * BJS is using an harcoded light falloff based on a manually sets up range.
  38365. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  38366. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  38367. */
  38368. _this._usePhysicalLightFalloff = true;
  38369. /**
  38370. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  38371. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  38372. */
  38373. _this._useRadianceOverAlpha = true;
  38374. /**
  38375. * Allows using the bump map in parallax mode.
  38376. */
  38377. _this._useParallax = false;
  38378. /**
  38379. * Allows using the bump map in parallax occlusion mode.
  38380. */
  38381. _this._useParallaxOcclusion = false;
  38382. /**
  38383. * Controls the scale bias of the parallax mode.
  38384. */
  38385. _this._parallaxScaleBias = 0.05;
  38386. /**
  38387. * If sets to true, disables all the lights affecting the material.
  38388. */
  38389. _this._disableLighting = false;
  38390. /**
  38391. * Number of Simultaneous lights allowed on the material.
  38392. */
  38393. _this._maxSimultaneousLights = 4;
  38394. /**
  38395. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38396. */
  38397. _this._invertNormalMapX = false;
  38398. /**
  38399. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38400. */
  38401. _this._invertNormalMapY = false;
  38402. /**
  38403. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38404. */
  38405. _this._twoSidedLighting = false;
  38406. /**
  38407. * Defines the alpha limits in alpha test mode.
  38408. */
  38409. _this._alphaCutOff = 0.4;
  38410. /**
  38411. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  38412. */
  38413. _this._forceAlphaTest = false;
  38414. /**
  38415. * If false, it allows the output of the shader to be in hdr space (e.g. more than one) which is usefull
  38416. * in combination of post process in float or half float mode.
  38417. */
  38418. _this._ldrOutput = true;
  38419. _this._renderTargets = new BABYLON.SmartArray(16);
  38420. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  38421. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38422. _this._tempColor = new BABYLON.Color3();
  38423. _this._defines = new PBRMaterialDefines();
  38424. _this._cachedDefines = new PBRMaterialDefines();
  38425. _this._myScene = null;
  38426. _this._myShadowGenerator = null;
  38427. _this._cachedDefines.BonesPerMesh = -1;
  38428. _this.getRenderTargetTextures = function () {
  38429. _this._renderTargets.reset();
  38430. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38431. _this._renderTargets.push(_this._reflectionTexture);
  38432. }
  38433. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38434. _this._renderTargets.push(_this._refractionTexture);
  38435. }
  38436. return _this._renderTargets;
  38437. };
  38438. return _this;
  38439. }
  38440. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  38441. get: function () {
  38442. return this._useLogarithmicDepth;
  38443. },
  38444. set: function (value) {
  38445. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  38446. },
  38447. enumerable: true,
  38448. configurable: true
  38449. });
  38450. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  38451. if (this._linkRefractionWithTransparency) {
  38452. return false;
  38453. }
  38454. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  38455. };
  38456. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  38457. if (this._linkRefractionWithTransparency) {
  38458. return false;
  38459. }
  38460. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  38461. };
  38462. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  38463. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  38464. };
  38465. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  38466. return this._albedoTexture;
  38467. };
  38468. PBRBaseMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  38469. if (!mesh) {
  38470. return true;
  38471. }
  38472. if (this._defines.INSTANCES !== useInstances) {
  38473. return false;
  38474. }
  38475. return false;
  38476. };
  38477. PBRBaseMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  38478. BABYLON.PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this._useScalarInLinearSpace);
  38479. };
  38480. PBRBaseMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  38481. if (!useScalarInLinear) {
  38482. color.toLinearSpaceToRef(ref);
  38483. }
  38484. else {
  38485. ref.r = color.r;
  38486. ref.g = color.g;
  38487. ref.b = color.b;
  38488. }
  38489. };
  38490. PBRBaseMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  38491. var lightIndex = 0;
  38492. var depthValuesAlreadySet = false;
  38493. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38494. var light = _a[_i];
  38495. var useUbo = light._uniformBuffer.useUbo;
  38496. var scaledIntensity = light.getScaledIntensity();
  38497. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  38498. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  38499. // GAMMA CORRECTION.
  38500. this.convertColorToLinearSpaceToRef(light.diffuse, BABYLON.PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  38501. BABYLON.PBRMaterial._scaledAlbedo.scaleToRef(scaledIntensity, BABYLON.PBRMaterial._scaledAlbedo);
  38502. light._uniformBuffer.updateColor4(useUbo ? "vLightDiffuse" : "vLightDiffuse" + lightIndex, BABYLON.PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  38503. if (defines["SPECULARTERM"]) {
  38504. this.convertColorToLinearSpaceToRef(light.specular, BABYLON.PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  38505. BABYLON.PBRMaterial._scaledReflectivity.scaleToRef(scaledIntensity, BABYLON.PBRMaterial._scaledReflectivity);
  38506. light._uniformBuffer.updateColor3(useUbo ? "vLightSpecular" : "vLightSpecular" + lightIndex, BABYLON.PBRMaterial._scaledReflectivity);
  38507. }
  38508. // Shadows
  38509. if (scene.shadowsEnabled) {
  38510. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex + "", effect, depthValuesAlreadySet);
  38511. }
  38512. light._uniformBuffer.update();
  38513. lightIndex++;
  38514. if (lightIndex === maxSimultaneousLights)
  38515. break;
  38516. }
  38517. };
  38518. PBRBaseMaterial.prototype.isReady = function (mesh, useInstances) {
  38519. if (this.isFrozen) {
  38520. if (this._wasPreviouslyReady) {
  38521. return true;
  38522. }
  38523. }
  38524. var scene = this.getScene();
  38525. var engine = scene.getEngine();
  38526. var needUVs = false;
  38527. this._defines.reset();
  38528. if (scene.lightsEnabled && !this._disableLighting) {
  38529. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, true, this._maxSimultaneousLights);
  38530. }
  38531. if (!this.checkReadyOnEveryCall) {
  38532. if (this._renderId === scene.getRenderId()) {
  38533. if (this._checkCache(scene, mesh, useInstances)) {
  38534. return true;
  38535. }
  38536. }
  38537. }
  38538. if (scene.texturesEnabled) {
  38539. if (scene.getEngine().getCaps().textureLOD) {
  38540. this._defines.LODBASEDMICROSFURACE = true;
  38541. }
  38542. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38543. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  38544. return false;
  38545. }
  38546. needUVs = true;
  38547. this._defines.ALBEDO = true;
  38548. }
  38549. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  38550. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  38551. return false;
  38552. }
  38553. needUVs = true;
  38554. this._defines.AMBIENT = true;
  38555. this._defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  38556. }
  38557. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  38558. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  38559. return false;
  38560. }
  38561. needUVs = true;
  38562. this._defines.OPACITY = true;
  38563. if (this._opacityTexture.getAlphaFromRGB) {
  38564. this._defines.OPACITYRGB = true;
  38565. }
  38566. }
  38567. var reflectionTexture = this._reflectionTexture || scene.environmentTexture;
  38568. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38569. if (!reflectionTexture.isReadyOrNotBlocking()) {
  38570. return false;
  38571. }
  38572. this._defines.REFLECTION = true;
  38573. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  38574. this._defines.INVERTCUBICMAP = true;
  38575. }
  38576. this._defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  38577. switch (reflectionTexture.coordinatesMode) {
  38578. case BABYLON.Texture.CUBIC_MODE:
  38579. case BABYLON.Texture.INVCUBIC_MODE:
  38580. this._defines.REFLECTIONMAP_CUBIC = true;
  38581. break;
  38582. case BABYLON.Texture.EXPLICIT_MODE:
  38583. this._defines.REFLECTIONMAP_EXPLICIT = true;
  38584. break;
  38585. case BABYLON.Texture.PLANAR_MODE:
  38586. this._defines.REFLECTIONMAP_PLANAR = true;
  38587. break;
  38588. case BABYLON.Texture.PROJECTION_MODE:
  38589. this._defines.REFLECTIONMAP_PROJECTION = true;
  38590. break;
  38591. case BABYLON.Texture.SKYBOX_MODE:
  38592. this._defines.REFLECTIONMAP_SKYBOX = true;
  38593. break;
  38594. case BABYLON.Texture.SPHERICAL_MODE:
  38595. this._defines.REFLECTIONMAP_SPHERICAL = true;
  38596. break;
  38597. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  38598. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  38599. break;
  38600. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  38601. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  38602. break;
  38603. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  38604. this._defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  38605. break;
  38606. }
  38607. if (reflectionTexture instanceof BABYLON.HDRCubeTexture && reflectionTexture) {
  38608. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  38609. if (reflectionTexture.isPMREM) {
  38610. this._defines.USEPMREMREFLECTION = true;
  38611. }
  38612. }
  38613. }
  38614. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  38615. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  38616. return false;
  38617. }
  38618. needUVs = true;
  38619. this._defines.LIGHTMAP = true;
  38620. this._defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  38621. }
  38622. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  38623. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  38624. return false;
  38625. }
  38626. needUVs = true;
  38627. this._defines.EMISSIVE = true;
  38628. }
  38629. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  38630. if (this._metallicTexture) {
  38631. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  38632. return false;
  38633. }
  38634. needUVs = true;
  38635. this._defines.METALLICWORKFLOW = true;
  38636. this._defines.METALLICMAP = true;
  38637. this._defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  38638. this._defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  38639. this._defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  38640. this._defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  38641. }
  38642. else if (this._reflectivityTexture) {
  38643. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  38644. return false;
  38645. }
  38646. needUVs = true;
  38647. this._defines.REFLECTIVITY = true;
  38648. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  38649. this._defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  38650. }
  38651. if (this._microSurfaceTexture) {
  38652. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  38653. return false;
  38654. }
  38655. needUVs = true;
  38656. this._defines.MICROSURFACEMAP = true;
  38657. }
  38658. }
  38659. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  38660. // Bump texure can not be none blocking.
  38661. if (!this._bumpTexture.isReady()) {
  38662. return false;
  38663. }
  38664. needUVs = true;
  38665. this._defines.BUMP = true;
  38666. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38667. this._defines.PARALLAX = true;
  38668. if (this._useParallaxOcclusion) {
  38669. this._defines.PARALLAXOCCLUSION = true;
  38670. }
  38671. }
  38672. if (this._invertNormalMapX) {
  38673. this._defines.INVERTNORMALMAPX = true;
  38674. }
  38675. if (this._invertNormalMapY) {
  38676. this._defines.INVERTNORMALMAPY = true;
  38677. }
  38678. if (scene._mirroredCameraPosition) {
  38679. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  38680. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  38681. }
  38682. this._defines.USERIGHTHANDEDSYSTEM = scene.useRightHandedSystem;
  38683. }
  38684. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  38685. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  38686. return false;
  38687. }
  38688. needUVs = true;
  38689. this._defines.REFRACTION = true;
  38690. this._defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  38691. if (this._linkRefractionWithTransparency) {
  38692. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  38693. }
  38694. if (this._refractionTexture instanceof BABYLON.HDRCubeTexture) {
  38695. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  38696. if (this._refractionTexture.isPMREM) {
  38697. this._defines.USEPMREMREFRACTION = true;
  38698. }
  38699. }
  38700. }
  38701. if (this._cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  38702. // Color Grading texure can not be none blocking.
  38703. if (!this._cameraColorGradingTexture.isReady()) {
  38704. return false;
  38705. }
  38706. this._defines.CAMERACOLORGRADING = true;
  38707. }
  38708. if (!this.backFaceCulling && this._twoSidedLighting) {
  38709. this._defines.TWOSIDEDLIGHTING = true;
  38710. }
  38711. }
  38712. this._defines.LDROUTPUT = this._ldrOutput;
  38713. // Effect
  38714. if (scene.clipPlane) {
  38715. this._defines.CLIPPLANE = true;
  38716. }
  38717. this._defines.ALPHATESTVALUE = this._alphaCutOff;
  38718. if (engine.getAlphaTesting() || this._forceAlphaTest) {
  38719. this._defines.ALPHATEST = true;
  38720. }
  38721. if (this._shouldUseAlphaFromAlbedoTexture()) {
  38722. this._defines.ALPHAFROMALBEDO = true;
  38723. }
  38724. if (this._useEmissiveAsIllumination) {
  38725. this._defines.EMISSIVEASILLUMINATION = true;
  38726. }
  38727. if (this.useLogarithmicDepth) {
  38728. this._defines.LOGARITHMICDEPTH = true;
  38729. }
  38730. if (this._cameraContrast != 1) {
  38731. this._defines.CAMERACONTRAST = true;
  38732. }
  38733. if (this._cameraExposure != 1) {
  38734. this._defines.CAMERATONEMAP = true;
  38735. }
  38736. if (this._cameraColorCurves) {
  38737. this._defines.CAMERACOLORCURVES = true;
  38738. }
  38739. // Point size
  38740. if (this.pointsCloud || scene.forcePointsCloud) {
  38741. this._defines.POINTSIZE = true;
  38742. }
  38743. // Fog
  38744. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  38745. this._defines.FOG = true;
  38746. }
  38747. if (BABYLON.StandardMaterial.FresnelEnabled) {
  38748. // Fresnel
  38749. if (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled ||
  38750. this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled) {
  38751. if (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled) {
  38752. this._defines.OPACITYFRESNEL = true;
  38753. }
  38754. if (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled) {
  38755. this._defines.EMISSIVEFRESNEL = true;
  38756. }
  38757. this._defines.FRESNEL = true;
  38758. }
  38759. }
  38760. if (this._defines.SPECULARTERM && this._useSpecularOverAlpha) {
  38761. this._defines.SPECULAROVERALPHA = true;
  38762. }
  38763. if (this._usePhysicalLightFalloff) {
  38764. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  38765. }
  38766. if (this._useRadianceOverAlpha) {
  38767. this._defines.RADIANCEOVERALPHA = true;
  38768. }
  38769. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  38770. this._defines.METALLICWORKFLOW = true;
  38771. }
  38772. // Attribs
  38773. if (mesh) {
  38774. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38775. mesh.createNormals(true);
  38776. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  38777. }
  38778. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38779. this._defines.NORMAL = true;
  38780. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38781. this._defines.TANGENT = true;
  38782. }
  38783. }
  38784. if (needUVs) {
  38785. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38786. this._defines.UV1 = true;
  38787. }
  38788. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38789. this._defines.UV2 = true;
  38790. }
  38791. }
  38792. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  38793. this._defines.VERTEXCOLOR = true;
  38794. if (mesh.hasVertexAlpha) {
  38795. this._defines.VERTEXALPHA = true;
  38796. }
  38797. }
  38798. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  38799. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  38800. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  38801. }
  38802. // Instances
  38803. if (useInstances) {
  38804. this._defines.INSTANCES = true;
  38805. }
  38806. if (mesh.morphTargetManager) {
  38807. var manager = mesh.morphTargetManager;
  38808. this._defines.MORPHTARGETS_TANGENT = manager.supportsTangents && this._defines.TANGENT;
  38809. this._defines.MORPHTARGETS_NORMAL = manager.supportsNormals && this._defines.NORMAL;
  38810. this._defines.MORPHTARGETS = (manager.numInfluencers > 0);
  38811. this._defines.NUM_MORPH_INFLUENCERS = manager.numInfluencers;
  38812. }
  38813. }
  38814. // Get correct effect
  38815. if (!this._defines.isEqual(this._cachedDefines)) {
  38816. this._defines.cloneTo(this._cachedDefines);
  38817. scene.resetCachedMaterial();
  38818. // Fallbacks
  38819. var fallbacks = new BABYLON.EffectFallbacks();
  38820. if (this._defines.REFLECTION) {
  38821. fallbacks.addFallback(0, "REFLECTION");
  38822. }
  38823. if (this._defines.REFRACTION) {
  38824. fallbacks.addFallback(0, "REFRACTION");
  38825. }
  38826. if (this._defines.REFLECTIVITY) {
  38827. fallbacks.addFallback(0, "REFLECTIVITY");
  38828. }
  38829. if (this._defines.BUMP) {
  38830. fallbacks.addFallback(0, "BUMP");
  38831. }
  38832. if (this._defines.PARALLAX) {
  38833. fallbacks.addFallback(1, "PARALLAX");
  38834. }
  38835. if (this._defines.PARALLAXOCCLUSION) {
  38836. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  38837. }
  38838. if (this._defines.SPECULAROVERALPHA) {
  38839. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  38840. }
  38841. if (this._defines.FOG) {
  38842. fallbacks.addFallback(1, "FOG");
  38843. }
  38844. if (this._defines.POINTSIZE) {
  38845. fallbacks.addFallback(0, "POINTSIZE");
  38846. }
  38847. if (this._defines.LOGARITHMICDEPTH) {
  38848. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  38849. }
  38850. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this._maxSimultaneousLights);
  38851. if (this._defines.SPECULARTERM) {
  38852. fallbacks.addFallback(0, "SPECULARTERM");
  38853. }
  38854. if (this._defines.OPACITYFRESNEL) {
  38855. fallbacks.addFallback(1, "OPACITYFRESNEL");
  38856. }
  38857. if (this._defines.EMISSIVEFRESNEL) {
  38858. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  38859. }
  38860. if (this._defines.FRESNEL) {
  38861. fallbacks.addFallback(3, "FRESNEL");
  38862. }
  38863. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  38864. fallbacks.addCPUSkinningFallback(0, mesh);
  38865. }
  38866. //Attributes
  38867. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38868. if (this._defines.NORMAL) {
  38869. attribs.push(BABYLON.VertexBuffer.NormalKind);
  38870. }
  38871. if (this._defines.TANGENT) {
  38872. attribs.push(BABYLON.VertexBuffer.TangentKind);
  38873. }
  38874. if (this._defines.UV1) {
  38875. attribs.push(BABYLON.VertexBuffer.UVKind);
  38876. }
  38877. if (this._defines.UV2) {
  38878. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38879. }
  38880. if (this._defines.VERTEXCOLOR) {
  38881. attribs.push(BABYLON.VertexBuffer.ColorKind);
  38882. }
  38883. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  38884. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  38885. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, this._defines);
  38886. // Legacy browser patch
  38887. var join = this._defines.toString();
  38888. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  38889. "vFogInfos", "vFogColor", "pointSize",
  38890. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  38891. "mBones",
  38892. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  38893. "depthValues",
  38894. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  38895. "vLightingIntensity",
  38896. "logarithmicDepthConstant",
  38897. "vSphericalX", "vSphericalY", "vSphericalZ",
  38898. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  38899. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  38900. "vMicrosurfaceTextureLods",
  38901. "vCameraInfos"
  38902. ];
  38903. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "microSurfaceSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  38904. var uniformBuffers = ["Material", "Scene"];
  38905. if (this._defines.CAMERACOLORCURVES) {
  38906. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  38907. }
  38908. if (this._defines.CAMERACOLORGRADING) {
  38909. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  38910. }
  38911. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  38912. uniformsNames: uniforms,
  38913. uniformBuffersNames: uniformBuffers,
  38914. samplers: samplers,
  38915. defines: this._defines,
  38916. maxSimultaneousLights: this._maxSimultaneousLights
  38917. });
  38918. var onCompiled = function (effect) {
  38919. if (this.onCompiled) {
  38920. this.onCompiled(effect);
  38921. }
  38922. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  38923. }.bind(this);
  38924. this._effect = scene.getEngine().createEffect("pbr", {
  38925. attributes: attribs,
  38926. uniformsNames: uniforms,
  38927. uniformBuffersNames: uniformBuffers,
  38928. samplers: samplers,
  38929. defines: join,
  38930. fallbacks: fallbacks,
  38931. onCompiled: onCompiled,
  38932. onError: this.onError,
  38933. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: this._defines.NUM_MORPH_INFLUENCERS }
  38934. }, engine);
  38935. this.buildUniformLayout();
  38936. }
  38937. if (!this._effect.isReady()) {
  38938. return false;
  38939. }
  38940. this._renderId = scene.getRenderId();
  38941. this._wasPreviouslyReady = true;
  38942. return true;
  38943. };
  38944. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  38945. // Order is important !
  38946. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  38947. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  38948. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  38949. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  38950. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  38951. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  38952. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  38953. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  38954. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  38955. this._uniformBuffer.addUniform("vBumpInfos", 3);
  38956. this._uniformBuffer.addUniform("albedoMatrix", 16);
  38957. this._uniformBuffer.addUniform("ambientMatrix", 16);
  38958. this._uniformBuffer.addUniform("opacityMatrix", 16);
  38959. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  38960. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  38961. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  38962. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  38963. this._uniformBuffer.addUniform("bumpMatrix", 16);
  38964. this._uniformBuffer.addUniform("refractionMatrix", 16);
  38965. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  38966. this._uniformBuffer.addUniform("vReflectionColor", 3);
  38967. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  38968. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  38969. this._uniformBuffer.addUniform("vMicrosurfaceTextureLods", 2);
  38970. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  38971. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  38972. this._uniformBuffer.addUniform("opacityParts", 4);
  38973. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  38974. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  38975. this._uniformBuffer.addUniform("pointSize", 1);
  38976. this._uniformBuffer.create();
  38977. };
  38978. PBRBaseMaterial.prototype.unbind = function () {
  38979. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  38980. this._uniformBuffer.setTexture("reflection2DSampler", null);
  38981. }
  38982. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  38983. this._uniformBuffer.setTexture("refraction2DSampler", null);
  38984. }
  38985. _super.prototype.unbind.call(this);
  38986. };
  38987. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38988. this._effect.setMatrix("world", world);
  38989. };
  38990. PBRBaseMaterial.prototype.bind = function (world, mesh) {
  38991. this._myScene = this.getScene();
  38992. var effect = this._effect;
  38993. // Matrices
  38994. this.bindOnlyWorldMatrix(world);
  38995. // Bones
  38996. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  38997. if (this._myScene.getCachedMaterial() !== this) {
  38998. this._uniformBuffer.bindToEffect(effect, "Material");
  38999. this.bindViewProjection(effect);
  39000. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39001. // Fresnel
  39002. if (BABYLON.StandardMaterial.FresnelEnabled) {
  39003. if (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled) {
  39004. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this._opacityFresnelParameters.leftColor.toLuminance(), this._opacityFresnelParameters.rightColor.toLuminance(), this._opacityFresnelParameters.bias), this._opacityFresnelParameters.power);
  39005. }
  39006. if (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled) {
  39007. this._uniformBuffer.updateColor4("emissiveLeftColor", this._emissiveFresnelParameters.leftColor, this._emissiveFresnelParameters.power);
  39008. this._uniformBuffer.updateColor4("emissiveRightColor", this._emissiveFresnelParameters.rightColor, this._emissiveFresnelParameters.bias);
  39009. }
  39010. }
  39011. // Texture uniforms
  39012. if (this._myScene.texturesEnabled) {
  39013. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  39014. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  39015. this._uniformBuffer.updateMatrix("albedoMatrix", this._albedoTexture.getTextureMatrix());
  39016. }
  39017. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  39018. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  39019. this._uniformBuffer.updateMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  39020. }
  39021. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  39022. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39023. this._uniformBuffer.updateMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  39024. }
  39025. var reflectionTexture = this._reflectionTexture || this._myScene.environmentTexture;
  39026. ;
  39027. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  39028. this._microsurfaceTextureLods.x = Math.round(Math.log(reflectionTexture.getSize().width) * Math.LOG2E);
  39029. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  39030. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  39031. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  39032. this._effect.setFloat3("vSphericalX", reflectionTexture.sphericalPolynomial.x.x, reflectionTexture.sphericalPolynomial.x.y, reflectionTexture.sphericalPolynomial.x.z);
  39033. this._effect.setFloat3("vSphericalY", reflectionTexture.sphericalPolynomial.y.x, reflectionTexture.sphericalPolynomial.y.y, reflectionTexture.sphericalPolynomial.y.z);
  39034. this._effect.setFloat3("vSphericalZ", reflectionTexture.sphericalPolynomial.z.x, reflectionTexture.sphericalPolynomial.z.y, reflectionTexture.sphericalPolynomial.z.z);
  39035. this._effect.setFloat3("vSphericalXX", reflectionTexture.sphericalPolynomial.xx.x, reflectionTexture.sphericalPolynomial.xx.y, reflectionTexture.sphericalPolynomial.xx.z);
  39036. this._effect.setFloat3("vSphericalYY", reflectionTexture.sphericalPolynomial.yy.x, reflectionTexture.sphericalPolynomial.yy.y, reflectionTexture.sphericalPolynomial.yy.z);
  39037. this._effect.setFloat3("vSphericalZZ", reflectionTexture.sphericalPolynomial.zz.x, reflectionTexture.sphericalPolynomial.zz.y, reflectionTexture.sphericalPolynomial.zz.z);
  39038. this._effect.setFloat3("vSphericalXY", reflectionTexture.sphericalPolynomial.xy.x, reflectionTexture.sphericalPolynomial.xy.y, reflectionTexture.sphericalPolynomial.xy.z);
  39039. this._effect.setFloat3("vSphericalYZ", reflectionTexture.sphericalPolynomial.yz.x, reflectionTexture.sphericalPolynomial.yz.y, reflectionTexture.sphericalPolynomial.yz.z);
  39040. this._effect.setFloat3("vSphericalZX", reflectionTexture.sphericalPolynomial.zx.x, reflectionTexture.sphericalPolynomial.zx.y, reflectionTexture.sphericalPolynomial.zx.z);
  39041. }
  39042. }
  39043. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  39044. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39045. this._uniformBuffer.updateMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  39046. }
  39047. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  39048. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39049. this._uniformBuffer.updateMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  39050. }
  39051. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  39052. if (this._metallicTexture) {
  39053. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  39054. this._uniformBuffer.updateMatrix("reflectivityMatrix", this._metallicTexture.getTextureMatrix());
  39055. }
  39056. else if (this._reflectivityTexture) {
  39057. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  39058. this._uniformBuffer.updateMatrix("reflectivityMatrix", this._reflectivityTexture.getTextureMatrix());
  39059. }
  39060. if (this._microSurfaceTexture) {
  39061. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  39062. this._uniformBuffer.updateMatrix("microSurfaceSamplerMatrix", this._microSurfaceTexture.getTextureMatrix());
  39063. }
  39064. }
  39065. if (this._bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  39066. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  39067. this._uniformBuffer.updateMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  39068. }
  39069. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  39070. this._microsurfaceTextureLods.y = Math.round(Math.log(this._refractionTexture.getSize().width) * Math.LOG2E);
  39071. var depth = 1.0;
  39072. if (!this._refractionTexture.isCube) {
  39073. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  39074. if (this._refractionTexture.depth) {
  39075. depth = this._refractionTexture.depth;
  39076. }
  39077. }
  39078. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  39079. }
  39080. if ((reflectionTexture || this._refractionTexture)) {
  39081. this._uniformBuffer.updateFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  39082. }
  39083. }
  39084. // Point size
  39085. if (this.pointsCloud) {
  39086. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39087. }
  39088. // Colors
  39089. if (this._defines.METALLICWORKFLOW) {
  39090. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  39091. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  39092. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  39093. }
  39094. else {
  39095. // GAMMA CORRECTION.
  39096. this.convertColorToLinearSpaceToRef(this._reflectivityColor, BABYLON.PBRMaterial._scaledReflectivity);
  39097. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, this._microSurface);
  39098. }
  39099. // GAMMA CORRECTION.
  39100. this.convertColorToLinearSpaceToRef(this._emissiveColor, BABYLON.PBRMaterial._scaledEmissive);
  39101. this._uniformBuffer.updateColor3("vEmissiveColor", BABYLON.PBRMaterial._scaledEmissive);
  39102. // GAMMA CORRECTION.
  39103. this.convertColorToLinearSpaceToRef(this._reflectionColor, BABYLON.PBRMaterial._scaledReflection);
  39104. this._uniformBuffer.updateColor3("vReflectionColor", BABYLON.PBRMaterial._scaledReflection);
  39105. // GAMMA CORRECTION.
  39106. this.convertColorToLinearSpaceToRef(this._albedoColor, BABYLON.PBRMaterial._scaledAlbedo);
  39107. this._uniformBuffer.updateColor4("vAlbedoColor", BABYLON.PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  39108. // Misc
  39109. this._lightingInfos.x = this._directIntensity;
  39110. this._lightingInfos.y = this._emissiveIntensity;
  39111. this._lightingInfos.z = this._environmentIntensity;
  39112. this._lightingInfos.w = this._specularIntensity;
  39113. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  39114. }
  39115. // Textures
  39116. if (this._myScene.texturesEnabled) {
  39117. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  39118. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  39119. }
  39120. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  39121. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  39122. }
  39123. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  39124. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  39125. }
  39126. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  39127. if (reflectionTexture.isCube) {
  39128. this._uniformBuffer.setTexture("reflectionCubeSampler", reflectionTexture);
  39129. }
  39130. else {
  39131. this._uniformBuffer.setTexture("reflection2DSampler", reflectionTexture);
  39132. }
  39133. }
  39134. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  39135. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  39136. }
  39137. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  39138. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  39139. }
  39140. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  39141. if (this._metallicTexture) {
  39142. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  39143. }
  39144. else if (this._reflectivityTexture) {
  39145. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  39146. }
  39147. if (this._microSurfaceTexture) {
  39148. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  39149. }
  39150. }
  39151. if (this._bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  39152. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  39153. }
  39154. if (this._refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  39155. if (this._refractionTexture.isCube) {
  39156. this._uniformBuffer.setTexture("refractionCubeSampler", this._refractionTexture);
  39157. }
  39158. else {
  39159. this._uniformBuffer.setTexture("refraction2DSampler", this._refractionTexture);
  39160. }
  39161. }
  39162. if (this._cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  39163. BABYLON.ColorGradingTexture.Bind(this._cameraColorGradingTexture, this._effect);
  39164. }
  39165. }
  39166. // Clip plane
  39167. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  39168. // Colors
  39169. this._myScene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  39170. effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  39171. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39172. }
  39173. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  39174. // Lights
  39175. if (this._myScene.lightsEnabled && !this._disableLighting) {
  39176. BABYLON.PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this._useScalarInLinearSpace, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  39177. }
  39178. // View
  39179. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  39180. this.bindView(effect);
  39181. }
  39182. // Fog
  39183. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  39184. // Morph targets
  39185. if (this._defines.NUM_MORPH_INFLUENCERS) {
  39186. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  39187. }
  39188. this._cameraInfos.x = this._cameraExposure;
  39189. this._cameraInfos.y = this._cameraContrast;
  39190. effect.setVector4("vCameraInfos", this._cameraInfos);
  39191. if (this._cameraColorCurves) {
  39192. BABYLON.ColorCurves.Bind(this._cameraColorCurves, this._effect);
  39193. }
  39194. // Log. depth
  39195. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  39196. }
  39197. this._uniformBuffer.update();
  39198. this._afterBind(mesh);
  39199. this._myScene = null;
  39200. };
  39201. PBRBaseMaterial.prototype.getAnimatables = function () {
  39202. var results = [];
  39203. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  39204. results.push(this._albedoTexture);
  39205. }
  39206. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39207. results.push(this._ambientTexture);
  39208. }
  39209. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39210. results.push(this._opacityTexture);
  39211. }
  39212. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39213. results.push(this._reflectionTexture);
  39214. }
  39215. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39216. results.push(this._emissiveTexture);
  39217. }
  39218. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  39219. results.push(this._metallicTexture);
  39220. }
  39221. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  39222. results.push(this._reflectivityTexture);
  39223. }
  39224. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39225. results.push(this._bumpTexture);
  39226. }
  39227. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39228. results.push(this._lightmapTexture);
  39229. }
  39230. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39231. results.push(this._refractionTexture);
  39232. }
  39233. if (this._cameraColorGradingTexture && this._cameraColorGradingTexture.animations && this._cameraColorGradingTexture.animations.length > 0) {
  39234. results.push(this._cameraColorGradingTexture);
  39235. }
  39236. return results;
  39237. };
  39238. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39239. if (forceDisposeTextures) {
  39240. if (this._albedoTexture) {
  39241. this._albedoTexture.dispose();
  39242. }
  39243. if (this._ambientTexture) {
  39244. this._ambientTexture.dispose();
  39245. }
  39246. if (this._opacityTexture) {
  39247. this._opacityTexture.dispose();
  39248. }
  39249. if (this._reflectionTexture) {
  39250. this._reflectionTexture.dispose();
  39251. }
  39252. if (this._emissiveTexture) {
  39253. this._emissiveTexture.dispose();
  39254. }
  39255. if (this._metallicTexture) {
  39256. this._metallicTexture.dispose();
  39257. }
  39258. if (this._reflectivityTexture) {
  39259. this._reflectivityTexture.dispose();
  39260. }
  39261. if (this._bumpTexture) {
  39262. this._bumpTexture.dispose();
  39263. }
  39264. if (this._lightmapTexture) {
  39265. this._lightmapTexture.dispose();
  39266. }
  39267. if (this._refractionTexture) {
  39268. this._refractionTexture.dispose();
  39269. }
  39270. if (this._cameraColorGradingTexture) {
  39271. this._cameraColorGradingTexture.dispose();
  39272. }
  39273. }
  39274. this._renderTargets.dispose();
  39275. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39276. };
  39277. return PBRBaseMaterial;
  39278. }(BABYLON.Material));
  39279. PBRBaseMaterial._scaledAlbedo = new BABYLON.Color3();
  39280. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  39281. PBRBaseMaterial._scaledEmissive = new BABYLON.Color3();
  39282. PBRBaseMaterial._scaledReflection = new BABYLON.Color3();
  39283. __decorate([
  39284. BABYLON.serialize()
  39285. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  39286. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  39287. })(BABYLON || (BABYLON = {}));
  39288. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  39289. var BABYLON;
  39290. (function (BABYLON) {
  39291. var Internals;
  39292. (function (Internals) {
  39293. /**
  39294. * The Physically based simple base material of BJS.
  39295. *
  39296. * This enables better naming and convention enforcements on top of the pbrMaterial.
  39297. * It is used as the base class for both the specGloss and metalRough conventions.
  39298. */
  39299. var PBRBaseSimpleMaterial = (function (_super) {
  39300. __extends(PBRBaseSimpleMaterial, _super);
  39301. /**
  39302. * Instantiates a new PBRMaterial instance.
  39303. *
  39304. * @param name The material name
  39305. * @param scene The scene the material will be use in.
  39306. */
  39307. function PBRBaseSimpleMaterial(name, scene) {
  39308. var _this = _super.call(this, name, scene) || this;
  39309. /**
  39310. * Number of Simultaneous lights allowed on the material.
  39311. */
  39312. _this.maxSimultaneousLights = 4;
  39313. /**
  39314. * If sets to true, disables all the lights affecting the material.
  39315. */
  39316. _this.disableLighting = false;
  39317. /**
  39318. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39319. */
  39320. _this.invertNormalMapX = false;
  39321. /**
  39322. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39323. */
  39324. _this.invertNormalMapY = false;
  39325. /**
  39326. * Emissivie color used to self-illuminate the model.
  39327. */
  39328. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39329. /**
  39330. * Occlusion Channel Strenght.
  39331. */
  39332. _this.occlusionStrength = 1.0;
  39333. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  39334. _this._useEmissiveAsIllumination = true;
  39335. _this._useAmbientInGrayScale = true;
  39336. _this._useScalarInLinearSpace = true;
  39337. return _this;
  39338. }
  39339. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  39340. /**
  39341. * Gets the current transparency mode.
  39342. */
  39343. get: function () {
  39344. return this._transparencyMode;
  39345. },
  39346. /**
  39347. * Sets the transparency mode of the material.
  39348. */
  39349. set: function (value) {
  39350. this._transparencyMode = value;
  39351. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  39352. this._forceAlphaTest = true;
  39353. }
  39354. else {
  39355. this._forceAlphaTest = false;
  39356. }
  39357. },
  39358. enumerable: true,
  39359. configurable: true
  39360. });
  39361. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  39362. /**
  39363. * Gets the current double sided mode.
  39364. */
  39365. get: function () {
  39366. return this._twoSidedLighting;
  39367. },
  39368. /**
  39369. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39370. */
  39371. set: function (value) {
  39372. this._twoSidedLighting = value;
  39373. this.backFaceCulling = !value;
  39374. },
  39375. enumerable: true,
  39376. configurable: true
  39377. });
  39378. /**
  39379. * Specifies wether or not the alpha value of the albedo texture should be used.
  39380. */
  39381. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  39382. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  39383. };
  39384. /**
  39385. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  39386. */
  39387. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  39388. if (this._linkRefractionWithTransparency) {
  39389. return false;
  39390. }
  39391. return (this.alpha < 1.0) ||
  39392. (this._shouldUseAlphaFromAlbedoTexture() &&
  39393. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  39394. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  39395. };
  39396. /**
  39397. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  39398. */
  39399. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  39400. if (this._linkRefractionWithTransparency) {
  39401. return false;
  39402. }
  39403. return this._shouldUseAlphaFromAlbedoTexture() &&
  39404. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  39405. };
  39406. return PBRBaseSimpleMaterial;
  39407. }(BABYLON.PBRBaseMaterial));
  39408. __decorate([
  39409. BABYLON.serialize(),
  39410. BABYLON.expandToProperty(null)
  39411. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  39412. __decorate([
  39413. BABYLON.serialize(),
  39414. BABYLON.expandToProperty(null)
  39415. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  39416. __decorate([
  39417. BABYLON.serializeAsTexture(),
  39418. BABYLON.expandToProperty(null, "_reflectionTexture")
  39419. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  39420. __decorate([
  39421. BABYLON.serialize(),
  39422. BABYLON.expandToProperty(null)
  39423. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  39424. __decorate([
  39425. BABYLON.serialize(),
  39426. BABYLON.expandToProperty(null)
  39427. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  39428. __decorate([
  39429. BABYLON.serializeAsTexture(),
  39430. BABYLON.expandToProperty(null, "_bumpTexture")
  39431. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  39432. __decorate([
  39433. BABYLON.serializeAsColor3("emissive"),
  39434. BABYLON.expandToProperty(null)
  39435. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  39436. __decorate([
  39437. BABYLON.serializeAsTexture(),
  39438. BABYLON.expandToProperty(null)
  39439. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  39440. __decorate([
  39441. BABYLON.serialize(),
  39442. BABYLON.expandToProperty(null, "_ambientTextureStrength")
  39443. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  39444. __decorate([
  39445. BABYLON.serializeAsTexture(),
  39446. BABYLON.expandToProperty(null, "_ambientTexture")
  39447. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  39448. __decorate([
  39449. BABYLON.serialize(),
  39450. BABYLON.expandToProperty(null, "_alphaCutOff")
  39451. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  39452. __decorate([
  39453. BABYLON.serialize()
  39454. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  39455. __decorate([
  39456. BABYLON.serialize()
  39457. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  39458. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  39459. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  39460. })(BABYLON || (BABYLON = {}));
  39461. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  39462. var BABYLON;
  39463. (function (BABYLON) {
  39464. /**
  39465. * The Physically based material of BJS.
  39466. *
  39467. * This offers the main features of a standard PBR material.
  39468. * For more information, please refer to the documentation :
  39469. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  39470. */
  39471. var PBRMaterial = (function (_super) {
  39472. __extends(PBRMaterial, _super);
  39473. /**
  39474. * Instantiates a new PBRMaterial instance.
  39475. *
  39476. * @param name The material name
  39477. * @param scene The scene the material will be use in.
  39478. */
  39479. function PBRMaterial(name, scene) {
  39480. var _this = _super.call(this, name, scene) || this;
  39481. /**
  39482. * Intensity of the direct lights e.g. the four lights available in your scene.
  39483. * This impacts both the direct diffuse and specular highlights.
  39484. */
  39485. _this.directIntensity = 1.0;
  39486. /**
  39487. * Intensity of the emissive part of the material.
  39488. * This helps controlling the emissive effect without modifying the emissive color.
  39489. */
  39490. _this.emissiveIntensity = 1.0;
  39491. /**
  39492. * Intensity of the environment e.g. how much the environment will light the object
  39493. * either through harmonics for rough material or through the refelction for shiny ones.
  39494. */
  39495. _this.environmentIntensity = 1.0;
  39496. /**
  39497. * This is a special control allowing the reduction of the specular highlights coming from the
  39498. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  39499. */
  39500. _this.specularIntensity = 1.0;
  39501. /**
  39502. * Debug Control allowing disabling the bump map on this material.
  39503. */
  39504. _this.disableBumpMap = false;
  39505. /**
  39506. * The camera exposure used on this material.
  39507. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39508. * This corresponds to a photographic exposure.
  39509. */
  39510. _this.cameraExposure = 1.0;
  39511. /**
  39512. * The camera contrast used on this material.
  39513. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  39514. */
  39515. _this.cameraContrast = 1.0;
  39516. /**
  39517. * Color Grading 2D Lookup Texture.
  39518. * This allows special effects like sepia, black and white to sixties rendering style.
  39519. */
  39520. _this.cameraColorGradingTexture = null;
  39521. /**
  39522. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39523. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39524. * 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;
  39525. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39526. */
  39527. _this.cameraColorCurves = null;
  39528. /**
  39529. * AKA Occlusion Texture Intensity in other nomenclature.
  39530. */
  39531. _this.ambientTextureStrength = 1.0;
  39532. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39533. /**
  39534. * AKA Diffuse Color in other nomenclature.
  39535. */
  39536. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  39537. /**
  39538. * AKA Specular Color in other nomenclature.
  39539. */
  39540. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  39541. _this.reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  39542. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39543. /**
  39544. * AKA Glossiness in other nomenclature.
  39545. */
  39546. _this.microSurface = 0.9;
  39547. /**
  39548. * source material index of refraction (IOR)' / 'destination material IOR.
  39549. */
  39550. _this.indexOfRefraction = 0.66;
  39551. /**
  39552. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  39553. */
  39554. _this.invertRefractionY = false;
  39555. /**
  39556. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  39557. * Materials half opaque for instance using refraction could benefit from this control.
  39558. */
  39559. _this.linkRefractionWithTransparency = false;
  39560. _this.useLightmapAsShadowmap = false;
  39561. /**
  39562. * In this mode, the emissive informtaion will always be added to the lighting once.
  39563. * A light for instance can be thought as emissive.
  39564. */
  39565. _this.useEmissiveAsIllumination = false;
  39566. /**
  39567. * Secifies that the alpha is coming form the albedo channel alpha channel.
  39568. */
  39569. _this.useAlphaFromAlbedoTexture = false;
  39570. /**
  39571. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  39572. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  39573. */
  39574. _this.useSpecularOverAlpha = true;
  39575. /**
  39576. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  39577. */
  39578. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  39579. /**
  39580. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  39581. */
  39582. _this.useRoughnessFromMetallicTextureAlpha = true;
  39583. /**
  39584. * Specifies if the metallic texture contains the roughness information in its green channel.
  39585. */
  39586. _this.useRoughnessFromMetallicTextureGreen = false;
  39587. /**
  39588. * Specifies if the metallic texture contains the metallness information in its blue channel.
  39589. */
  39590. _this.useMetallnessFromMetallicTextureBlue = false;
  39591. /**
  39592. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  39593. */
  39594. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  39595. /**
  39596. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  39597. */
  39598. _this.useAmbientInGrayScale = false;
  39599. /**
  39600. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  39601. * The material will try to infer what glossiness each pixel should be.
  39602. */
  39603. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  39604. /**
  39605. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  39606. * the creation of the material.
  39607. */
  39608. _this.useScalarInLinearSpace = false;
  39609. /**
  39610. * BJS is using an harcoded light falloff based on a manually sets up range.
  39611. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  39612. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  39613. */
  39614. _this.usePhysicalLightFalloff = true;
  39615. /**
  39616. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  39617. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  39618. */
  39619. _this.useRadianceOverAlpha = true;
  39620. /**
  39621. * Allows using the bump map in parallax mode.
  39622. */
  39623. _this.useParallax = false;
  39624. /**
  39625. * Allows using the bump map in parallax occlusion mode.
  39626. */
  39627. _this.useParallaxOcclusion = false;
  39628. /**
  39629. * Controls the scale bias of the parallax mode.
  39630. */
  39631. _this.parallaxScaleBias = 0.05;
  39632. /**
  39633. * If sets to true, disables all the lights affecting the material.
  39634. */
  39635. _this.disableLighting = false;
  39636. /**
  39637. * Number of Simultaneous lights allowed on the material.
  39638. */
  39639. _this.maxSimultaneousLights = 4;
  39640. /**
  39641. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39642. */
  39643. _this.invertNormalMapX = false;
  39644. /**
  39645. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39646. */
  39647. _this.invertNormalMapY = false;
  39648. /**
  39649. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39650. */
  39651. _this.twoSidedLighting = false;
  39652. return _this;
  39653. }
  39654. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  39655. /**
  39656. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  39657. */
  39658. get: function () {
  39659. return this._PBRMATERIAL_OPAQUE;
  39660. },
  39661. enumerable: true,
  39662. configurable: true
  39663. });
  39664. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  39665. /**
  39666. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  39667. */
  39668. get: function () {
  39669. return this._PBRMATERIAL_ALPHATEST;
  39670. },
  39671. enumerable: true,
  39672. configurable: true
  39673. });
  39674. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  39675. /**
  39676. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  39677. */
  39678. get: function () {
  39679. return this._PBRMATERIAL_ALPHABLEND;
  39680. },
  39681. enumerable: true,
  39682. configurable: true
  39683. });
  39684. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  39685. /**
  39686. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  39687. * They are also discarded below the alpha cutoff threshold to improve performances.
  39688. */
  39689. get: function () {
  39690. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  39691. },
  39692. enumerable: true,
  39693. configurable: true
  39694. });
  39695. PBRMaterial.prototype.getClassName = function () {
  39696. return "PBRMaterial";
  39697. };
  39698. PBRMaterial.prototype.clone = function (name) {
  39699. var _this = this;
  39700. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  39701. };
  39702. PBRMaterial.prototype.serialize = function () {
  39703. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39704. serializationObject.customType = "BABYLON.PBRMaterial";
  39705. return serializationObject;
  39706. };
  39707. // Statics
  39708. PBRMaterial.Parse = function (source, scene, rootUrl) {
  39709. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  39710. };
  39711. return PBRMaterial;
  39712. }(BABYLON.PBRBaseMaterial));
  39713. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  39714. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  39715. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  39716. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  39717. __decorate([
  39718. BABYLON.serialize(),
  39719. BABYLON.expandToProperty(null)
  39720. ], PBRMaterial.prototype, "directIntensity", void 0);
  39721. __decorate([
  39722. BABYLON.serialize(),
  39723. BABYLON.expandToProperty(null)
  39724. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  39725. __decorate([
  39726. BABYLON.serialize(),
  39727. BABYLON.expandToProperty(null)
  39728. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  39729. __decorate([
  39730. BABYLON.serialize(),
  39731. BABYLON.expandToProperty(null)
  39732. ], PBRMaterial.prototype, "specularIntensity", void 0);
  39733. __decorate([
  39734. BABYLON.serialize(),
  39735. BABYLON.expandToProperty(null)
  39736. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  39737. __decorate([
  39738. BABYLON.serialize(),
  39739. BABYLON.expandToProperty(null)
  39740. ], PBRMaterial.prototype, "cameraExposure", void 0);
  39741. __decorate([
  39742. BABYLON.serialize(),
  39743. BABYLON.expandToProperty(null)
  39744. ], PBRMaterial.prototype, "cameraContrast", void 0);
  39745. __decorate([
  39746. BABYLON.serializeAsTexture(),
  39747. BABYLON.expandToProperty(null)
  39748. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  39749. __decorate([
  39750. BABYLON.serializeAsColorCurves(),
  39751. BABYLON.expandToProperty(null)
  39752. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  39753. __decorate([
  39754. BABYLON.serializeAsTexture(),
  39755. BABYLON.expandToProperty(null)
  39756. ], PBRMaterial.prototype, "albedoTexture", void 0);
  39757. __decorate([
  39758. BABYLON.serializeAsTexture(),
  39759. BABYLON.expandToProperty(null)
  39760. ], PBRMaterial.prototype, "ambientTexture", void 0);
  39761. __decorate([
  39762. BABYLON.serialize(),
  39763. BABYLON.expandToProperty(null)
  39764. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  39765. __decorate([
  39766. BABYLON.serializeAsTexture(),
  39767. BABYLON.expandToProperty(null)
  39768. ], PBRMaterial.prototype, "opacityTexture", void 0);
  39769. __decorate([
  39770. BABYLON.serializeAsTexture(),
  39771. BABYLON.expandToProperty(null)
  39772. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  39773. __decorate([
  39774. BABYLON.serializeAsTexture(),
  39775. BABYLON.expandToProperty(null)
  39776. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  39777. __decorate([
  39778. BABYLON.serializeAsTexture(),
  39779. BABYLON.expandToProperty(null)
  39780. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  39781. __decorate([
  39782. BABYLON.serializeAsTexture(),
  39783. BABYLON.expandToProperty(null)
  39784. ], PBRMaterial.prototype, "metallicTexture", void 0);
  39785. __decorate([
  39786. BABYLON.serialize(),
  39787. BABYLON.expandToProperty(null)
  39788. ], PBRMaterial.prototype, "metallic", void 0);
  39789. __decorate([
  39790. BABYLON.serialize(),
  39791. BABYLON.expandToProperty(null)
  39792. ], PBRMaterial.prototype, "roughness", void 0);
  39793. __decorate([
  39794. BABYLON.serializeAsTexture(),
  39795. BABYLON.expandToProperty(null)
  39796. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  39797. __decorate([
  39798. BABYLON.serializeAsTexture(),
  39799. BABYLON.expandToProperty(null)
  39800. ], PBRMaterial.prototype, "bumpTexture", void 0);
  39801. __decorate([
  39802. BABYLON.serializeAsTexture(),
  39803. BABYLON.expandToProperty(null)
  39804. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  39805. __decorate([
  39806. BABYLON.serializeAsTexture(),
  39807. BABYLON.expandToProperty(null)
  39808. ], PBRMaterial.prototype, "refractionTexture", void 0);
  39809. __decorate([
  39810. BABYLON.serializeAsColor3("ambient"),
  39811. BABYLON.expandToProperty(null)
  39812. ], PBRMaterial.prototype, "ambientColor", void 0);
  39813. __decorate([
  39814. BABYLON.serializeAsColor3("albedo"),
  39815. BABYLON.expandToProperty(null)
  39816. ], PBRMaterial.prototype, "albedoColor", void 0);
  39817. __decorate([
  39818. BABYLON.serializeAsColor3("reflectivity"),
  39819. BABYLON.expandToProperty(null)
  39820. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  39821. __decorate([
  39822. BABYLON.serializeAsColor3("reflection"),
  39823. BABYLON.expandToProperty(null)
  39824. ], PBRMaterial.prototype, "reflectionColor", void 0);
  39825. __decorate([
  39826. BABYLON.serializeAsColor3("emissive"),
  39827. BABYLON.expandToProperty(null)
  39828. ], PBRMaterial.prototype, "emissiveColor", void 0);
  39829. __decorate([
  39830. BABYLON.serialize(),
  39831. BABYLON.expandToProperty(null)
  39832. ], PBRMaterial.prototype, "microSurface", void 0);
  39833. __decorate([
  39834. BABYLON.serialize(),
  39835. BABYLON.expandToProperty(null)
  39836. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  39837. __decorate([
  39838. BABYLON.serialize(),
  39839. BABYLON.expandToProperty(null)
  39840. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  39841. __decorate([
  39842. BABYLON.serializeAsFresnelParameters(),
  39843. BABYLON.expandToProperty(null)
  39844. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  39845. __decorate([
  39846. BABYLON.serializeAsFresnelParameters(),
  39847. BABYLON.expandToProperty(null)
  39848. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  39849. __decorate([
  39850. BABYLON.serialize(),
  39851. BABYLON.expandToProperty(null)
  39852. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  39853. __decorate([
  39854. BABYLON.serialize(),
  39855. BABYLON.expandToProperty(null)
  39856. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39857. __decorate([
  39858. BABYLON.serialize(),
  39859. BABYLON.expandToProperty(null)
  39860. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  39861. __decorate([
  39862. BABYLON.serialize(),
  39863. BABYLON.expandToProperty(null)
  39864. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  39865. __decorate([
  39866. BABYLON.serialize(),
  39867. BABYLON.expandToProperty(null)
  39868. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  39869. __decorate([
  39870. BABYLON.serialize(),
  39871. BABYLON.expandToProperty(null)
  39872. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  39873. __decorate([
  39874. BABYLON.serialize(),
  39875. BABYLON.expandToProperty(null)
  39876. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  39877. __decorate([
  39878. BABYLON.serialize(),
  39879. BABYLON.expandToProperty(null)
  39880. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  39881. __decorate([
  39882. BABYLON.serialize(),
  39883. BABYLON.expandToProperty(null)
  39884. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  39885. __decorate([
  39886. BABYLON.serialize(),
  39887. BABYLON.expandToProperty(null)
  39888. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  39889. __decorate([
  39890. BABYLON.serialize(),
  39891. BABYLON.expandToProperty(null)
  39892. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  39893. __decorate([
  39894. BABYLON.serialize(),
  39895. BABYLON.expandToProperty(null)
  39896. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  39897. __decorate([
  39898. BABYLON.serialize(),
  39899. BABYLON.expandToProperty(null)
  39900. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  39901. __decorate([
  39902. BABYLON.serialize(),
  39903. BABYLON.expandToProperty(null)
  39904. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  39905. __decorate([
  39906. BABYLON.serialize(),
  39907. BABYLON.expandToProperty(null)
  39908. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  39909. __decorate([
  39910. BABYLON.serialize(),
  39911. BABYLON.expandToProperty(null)
  39912. ], PBRMaterial.prototype, "useParallax", void 0);
  39913. __decorate([
  39914. BABYLON.serialize(),
  39915. BABYLON.expandToProperty(null)
  39916. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  39917. __decorate([
  39918. BABYLON.serialize(),
  39919. BABYLON.expandToProperty(null)
  39920. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  39921. __decorate([
  39922. BABYLON.serialize(),
  39923. BABYLON.expandToProperty(null)
  39924. ], PBRMaterial.prototype, "disableLighting", void 0);
  39925. __decorate([
  39926. BABYLON.serialize(),
  39927. BABYLON.expandToProperty(null)
  39928. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  39929. __decorate([
  39930. BABYLON.serialize(),
  39931. BABYLON.expandToProperty(null)
  39932. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  39933. __decorate([
  39934. BABYLON.serialize(),
  39935. BABYLON.expandToProperty(null)
  39936. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  39937. __decorate([
  39938. BABYLON.serialize(),
  39939. BABYLON.expandToProperty(null)
  39940. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  39941. BABYLON.PBRMaterial = PBRMaterial;
  39942. })(BABYLON || (BABYLON = {}));
  39943. //# sourceMappingURL=babylon.pbrMaterial.js.map
  39944. var BABYLON;
  39945. (function (BABYLON) {
  39946. /**
  39947. * The PBR material of BJS following the metal roughness convention.
  39948. *
  39949. * This fits to the define PBR convention in the GLTF definition:
  39950. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  39951. */
  39952. var PBRMetallicRoughnessMaterial = (function (_super) {
  39953. __extends(PBRMetallicRoughnessMaterial, _super);
  39954. /**
  39955. * Instantiates a new PBRMetalRoughnessMaterial instance.
  39956. *
  39957. * @param name The material name
  39958. * @param scene The scene the material will be use in.
  39959. */
  39960. function PBRMetallicRoughnessMaterial(name, scene) {
  39961. var _this = _super.call(this, name, scene) || this;
  39962. _this._useRoughnessFromMetallicTextureGreen = true;
  39963. _this._useMetallnessFromMetallicTextureBlue = true;
  39964. return _this;
  39965. }
  39966. /**
  39967. * Return the currrent class name of the material.
  39968. */
  39969. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  39970. return "PBRMetallicRoughnessMaterial";
  39971. };
  39972. /**
  39973. * Serialize the material to a parsable JSON object.
  39974. */
  39975. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  39976. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39977. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  39978. return serializationObject;
  39979. };
  39980. /**
  39981. * Parses a JSON object correponding to the serialize function.
  39982. */
  39983. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  39984. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  39985. };
  39986. return PBRMetallicRoughnessMaterial;
  39987. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  39988. __decorate([
  39989. BABYLON.serializeAsTexture(),
  39990. BABYLON.expandToProperty(null, "_albedoColor")
  39991. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  39992. __decorate([
  39993. BABYLON.serializeAsTexture(),
  39994. BABYLON.expandToProperty(null, "_albedoTexture")
  39995. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  39996. __decorate([
  39997. BABYLON.serialize(),
  39998. BABYLON.expandToProperty(null)
  39999. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  40000. __decorate([
  40001. BABYLON.serialize(),
  40002. BABYLON.expandToProperty(null)
  40003. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  40004. __decorate([
  40005. BABYLON.serializeAsTexture(),
  40006. BABYLON.expandToProperty(null, "_metallicTexture")
  40007. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  40008. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  40009. })(BABYLON || (BABYLON = {}));
  40010. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  40011. var BABYLON;
  40012. (function (BABYLON) {
  40013. /**
  40014. * The PBR material of BJS following the specular glossiness convention.
  40015. *
  40016. * This fits to the define PBR convention in the GLTF definition:
  40017. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  40018. */
  40019. var PBRSpecularGlossinessMaterial = (function (_super) {
  40020. __extends(PBRSpecularGlossinessMaterial, _super);
  40021. /**
  40022. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  40023. *
  40024. * @param name The material name
  40025. * @param scene The scene the material will be use in.
  40026. */
  40027. function PBRSpecularGlossinessMaterial(name, scene) {
  40028. var _this = _super.call(this, name, scene) || this;
  40029. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  40030. return _this;
  40031. }
  40032. /**
  40033. * Return the currrent class name of the material.
  40034. */
  40035. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  40036. return "PBRSpecularGlossinessMaterial";
  40037. };
  40038. /**
  40039. * Serialize the material to a parsable JSON object.
  40040. */
  40041. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  40042. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40043. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  40044. return serializationObject;
  40045. };
  40046. /**
  40047. * Parses a JSON object correponding to the serialize function.
  40048. */
  40049. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  40050. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  40051. };
  40052. return PBRSpecularGlossinessMaterial;
  40053. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  40054. __decorate([
  40055. BABYLON.serializeAsColor3(),
  40056. BABYLON.expandToProperty(null, "_albedoColor")
  40057. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  40058. __decorate([
  40059. BABYLON.serializeAsTexture(),
  40060. BABYLON.expandToProperty(null, "_albedoTexture")
  40061. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  40062. __decorate([
  40063. BABYLON.serializeAsColor3(),
  40064. BABYLON.expandToProperty(null, "_reflectivityColor")
  40065. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  40066. __decorate([
  40067. BABYLON.serialize(),
  40068. BABYLON.expandToProperty(null, "_microSurface")
  40069. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  40070. __decorate([
  40071. BABYLON.serializeAsTexture(),
  40072. BABYLON.expandToProperty(null, "_reflectivityTexture")
  40073. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  40074. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  40075. })(BABYLON || (BABYLON = {}));
  40076. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  40077. var BABYLON;
  40078. (function (BABYLON) {
  40079. var ShadowLight = (function (_super) {
  40080. __extends(ShadowLight, _super);
  40081. function ShadowLight() {
  40082. var _this = _super !== null && _super.apply(this, arguments) || this;
  40083. _this._needProjectionMatrixCompute = true;
  40084. return _this;
  40085. }
  40086. Object.defineProperty(ShadowLight.prototype, "direction", {
  40087. get: function () {
  40088. return this._direction;
  40089. },
  40090. set: function (value) {
  40091. this._direction = value;
  40092. },
  40093. enumerable: true,
  40094. configurable: true
  40095. });
  40096. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  40097. get: function () {
  40098. return this._shadowMinZ;
  40099. },
  40100. set: function (value) {
  40101. this._shadowMinZ = value;
  40102. this.forceProjectionMatrixCompute();
  40103. },
  40104. enumerable: true,
  40105. configurable: true
  40106. });
  40107. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  40108. get: function () {
  40109. return this._shadowMaxZ;
  40110. },
  40111. set: function (value) {
  40112. this._shadowMaxZ = value;
  40113. this.forceProjectionMatrixCompute();
  40114. },
  40115. enumerable: true,
  40116. configurable: true
  40117. });
  40118. /**
  40119. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  40120. */
  40121. ShadowLight.prototype.computeTransformedInformation = function () {
  40122. if (this.parent && this.parent.getWorldMatrix) {
  40123. if (!this.transformedPosition) {
  40124. this.transformedPosition = BABYLON.Vector3.Zero();
  40125. }
  40126. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  40127. // In case the direction is present.
  40128. if (this.direction) {
  40129. if (!this.transformedDirection) {
  40130. this.transformedDirection = BABYLON.Vector3.Zero();
  40131. }
  40132. BABYLON.Vector3.TransformCoordinatesToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  40133. }
  40134. return true;
  40135. }
  40136. return false;
  40137. };
  40138. /**
  40139. * Return the depth scale used for the shadow map.
  40140. */
  40141. ShadowLight.prototype.getDepthScale = function () {
  40142. return 30.0;
  40143. };
  40144. /**
  40145. * Returns the light direction (Vector3) for any passed face index.
  40146. */
  40147. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  40148. return this.transformedDirection ? this.transformedDirection : this.direction;
  40149. };
  40150. /**
  40151. * Returns the DirectionalLight absolute position in the World.
  40152. */
  40153. ShadowLight.prototype.getAbsolutePosition = function () {
  40154. return this.transformedPosition ? this.transformedPosition : this.position;
  40155. };
  40156. /**
  40157. * Sets the DirectionalLight direction toward the passed target (Vector3).
  40158. * Returns the updated DirectionalLight direction (Vector3).
  40159. */
  40160. ShadowLight.prototype.setDirectionToTarget = function (target) {
  40161. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  40162. return this.direction;
  40163. };
  40164. /**
  40165. * Returns the light rotation (Vector3).
  40166. */
  40167. ShadowLight.prototype.getRotation = function () {
  40168. this.direction.normalize();
  40169. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  40170. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  40171. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  40172. };
  40173. /**
  40174. * Boolean : false by default.
  40175. */
  40176. ShadowLight.prototype.needCube = function () {
  40177. return false;
  40178. };
  40179. /**
  40180. * Specifies wether or not the projection matrix should be recomputed this frame.
  40181. */
  40182. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  40183. return this._needProjectionMatrixCompute;
  40184. };
  40185. /**
  40186. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  40187. */
  40188. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  40189. this._needProjectionMatrixCompute = true;
  40190. };
  40191. /**
  40192. * Get the world matrix of the sahdow lights.
  40193. */
  40194. ShadowLight.prototype._getWorldMatrix = function () {
  40195. if (!this._worldMatrix) {
  40196. this._worldMatrix = BABYLON.Matrix.Identity();
  40197. }
  40198. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  40199. return this._worldMatrix;
  40200. };
  40201. /**
  40202. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  40203. * Returns the light.
  40204. */
  40205. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40206. if (this.customProjectionMatrixBuilder) {
  40207. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  40208. }
  40209. else {
  40210. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  40211. }
  40212. return this;
  40213. };
  40214. return ShadowLight;
  40215. }(BABYLON.Light));
  40216. __decorate([
  40217. BABYLON.serializeAsVector3()
  40218. ], ShadowLight.prototype, "position", void 0);
  40219. __decorate([
  40220. BABYLON.serializeAsVector3()
  40221. ], ShadowLight.prototype, "direction", null);
  40222. __decorate([
  40223. BABYLON.serialize()
  40224. ], ShadowLight.prototype, "shadowMinZ", null);
  40225. __decorate([
  40226. BABYLON.serialize()
  40227. ], ShadowLight.prototype, "shadowMaxZ", null);
  40228. BABYLON.ShadowLight = ShadowLight;
  40229. })(BABYLON || (BABYLON = {}));
  40230. //# sourceMappingURL=babylon.shadowLight.js.map
  40231. var BABYLON;
  40232. (function (BABYLON) {
  40233. var PointLight = (function (_super) {
  40234. __extends(PointLight, _super);
  40235. /**
  40236. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  40237. * A PointLight emits the light in every direction.
  40238. * It can cast shadows.
  40239. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  40240. * ```javascript
  40241. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  40242. * ```
  40243. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40244. */
  40245. function PointLight(name, position, scene) {
  40246. var _this = _super.call(this, name, scene) || this;
  40247. _this._shadowAngle = Math.PI / 2;
  40248. _this.position = position;
  40249. return _this;
  40250. }
  40251. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  40252. /**
  40253. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40254. * This specifies what angle the shadow will use to be created.
  40255. *
  40256. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  40257. */
  40258. get: function () {
  40259. return this._shadowAngle;
  40260. },
  40261. /**
  40262. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40263. * This specifies what angle the shadow will use to be created.
  40264. *
  40265. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  40266. */
  40267. set: function (value) {
  40268. this._shadowAngle = value;
  40269. this.forceProjectionMatrixCompute();
  40270. },
  40271. enumerable: true,
  40272. configurable: true
  40273. });
  40274. Object.defineProperty(PointLight.prototype, "direction", {
  40275. get: function () {
  40276. return this._direction;
  40277. },
  40278. /**
  40279. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40280. */
  40281. set: function (value) {
  40282. var previousNeedCube = this.needCube();
  40283. this._direction = value;
  40284. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  40285. this._shadowGenerator.recreateShadowMap();
  40286. }
  40287. },
  40288. enumerable: true,
  40289. configurable: true
  40290. });
  40291. /**
  40292. * Returns the string "PointLight"
  40293. */
  40294. PointLight.prototype.getClassName = function () {
  40295. return "PointLight";
  40296. };
  40297. /**
  40298. * Returns the integer 0.
  40299. */
  40300. PointLight.prototype.getTypeID = function () {
  40301. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  40302. };
  40303. /**
  40304. * Specifies wether or not the shadowmap should be a cube texture.
  40305. */
  40306. PointLight.prototype.needCube = function () {
  40307. return !this.direction;
  40308. };
  40309. /**
  40310. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  40311. */
  40312. PointLight.prototype.getShadowDirection = function (faceIndex) {
  40313. if (this.direction) {
  40314. return _super.prototype.getShadowDirection.call(this, faceIndex);
  40315. }
  40316. else {
  40317. switch (faceIndex) {
  40318. case 0:
  40319. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  40320. case 1:
  40321. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  40322. case 2:
  40323. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  40324. case 3:
  40325. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  40326. case 4:
  40327. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  40328. case 5:
  40329. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  40330. }
  40331. }
  40332. return BABYLON.Vector3.Zero();
  40333. };
  40334. /**
  40335. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  40336. * - fov = PI / 2
  40337. * - aspect ratio : 1.0
  40338. * - z-near and far equal to the active camera minZ and maxZ.
  40339. * Returns the PointLight.
  40340. */
  40341. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40342. var activeCamera = this.getScene().activeCamera;
  40343. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  40344. };
  40345. PointLight.prototype._buildUniformLayout = function () {
  40346. this._uniformBuffer.addUniform("vLightData", 4);
  40347. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40348. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40349. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40350. this._uniformBuffer.create();
  40351. };
  40352. /**
  40353. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  40354. * Returns the PointLight.
  40355. */
  40356. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  40357. if (this.computeTransformedInformation()) {
  40358. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  40359. return this;
  40360. }
  40361. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  40362. return this;
  40363. };
  40364. return PointLight;
  40365. }(BABYLON.ShadowLight));
  40366. __decorate([
  40367. BABYLON.serialize()
  40368. ], PointLight.prototype, "shadowAngle", null);
  40369. BABYLON.PointLight = PointLight;
  40370. })(BABYLON || (BABYLON = {}));
  40371. //# sourceMappingURL=babylon.pointLight.js.map
  40372. /// <reference path="babylon.light.ts" />
  40373. var BABYLON;
  40374. (function (BABYLON) {
  40375. var DirectionalLight = (function (_super) {
  40376. __extends(DirectionalLight, _super);
  40377. /**
  40378. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  40379. * The directional light is emitted from everywhere in the given direction.
  40380. * It can cast shawdows.
  40381. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40382. */
  40383. function DirectionalLight(name, direction, scene) {
  40384. var _this = _super.call(this, name, scene) || this;
  40385. _this._shadowOrthoScale = 0.5;
  40386. _this.autoUpdateExtends = true;
  40387. // Cache
  40388. _this._orthoLeft = Number.MAX_VALUE;
  40389. _this._orthoRight = Number.MIN_VALUE;
  40390. _this._orthoTop = Number.MIN_VALUE;
  40391. _this._orthoBottom = Number.MAX_VALUE;
  40392. _this.position = direction.scale(-1.0);
  40393. _this.direction = direction;
  40394. return _this;
  40395. }
  40396. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  40397. get: function () {
  40398. return this._shadowOrthoScale;
  40399. },
  40400. set: function (value) {
  40401. this._shadowOrthoScale = value;
  40402. this.forceProjectionMatrixCompute();
  40403. },
  40404. enumerable: true,
  40405. configurable: true
  40406. });
  40407. /**
  40408. * Returns the string "DirectionalLight".
  40409. */
  40410. DirectionalLight.prototype.getClassName = function () {
  40411. return "DirectionalLight";
  40412. };
  40413. /**
  40414. * Returns the integer 1.
  40415. */
  40416. DirectionalLight.prototype.getTypeID = function () {
  40417. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  40418. };
  40419. /**
  40420. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  40421. * Returns the DirectionalLight.
  40422. */
  40423. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40424. var activeCamera = this.getScene().activeCamera;
  40425. // Check extends
  40426. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  40427. var tempVector3 = BABYLON.Vector3.Zero();
  40428. this._orthoLeft = Number.MAX_VALUE;
  40429. this._orthoRight = Number.MIN_VALUE;
  40430. this._orthoTop = Number.MIN_VALUE;
  40431. this._orthoBottom = Number.MAX_VALUE;
  40432. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  40433. var mesh = renderList[meshIndex];
  40434. if (!mesh) {
  40435. continue;
  40436. }
  40437. var boundingInfo = mesh.getBoundingInfo();
  40438. if (!boundingInfo) {
  40439. continue;
  40440. }
  40441. var boundingBox = boundingInfo.boundingBox;
  40442. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  40443. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  40444. if (tempVector3.x < this._orthoLeft)
  40445. this._orthoLeft = tempVector3.x;
  40446. if (tempVector3.y < this._orthoBottom)
  40447. this._orthoBottom = tempVector3.y;
  40448. if (tempVector3.x > this._orthoRight)
  40449. this._orthoRight = tempVector3.x;
  40450. if (tempVector3.y > this._orthoTop)
  40451. this._orthoTop = tempVector3.y;
  40452. }
  40453. }
  40454. }
  40455. var xOffset = this._orthoRight - this._orthoLeft;
  40456. var yOffset = this._orthoTop - this._orthoBottom;
  40457. 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);
  40458. };
  40459. DirectionalLight.prototype._buildUniformLayout = function () {
  40460. this._uniformBuffer.addUniform("vLightData", 4);
  40461. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40462. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40463. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40464. this._uniformBuffer.create();
  40465. };
  40466. /**
  40467. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  40468. * Returns the DirectionalLight.
  40469. */
  40470. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  40471. if (this.computeTransformedInformation()) {
  40472. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  40473. return this;
  40474. }
  40475. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  40476. return this;
  40477. };
  40478. return DirectionalLight;
  40479. }(BABYLON.ShadowLight));
  40480. __decorate([
  40481. BABYLON.serialize()
  40482. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  40483. __decorate([
  40484. BABYLON.serialize()
  40485. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  40486. BABYLON.DirectionalLight = DirectionalLight;
  40487. })(BABYLON || (BABYLON = {}));
  40488. //# sourceMappingURL=babylon.directionalLight.js.map
  40489. var BABYLON;
  40490. (function (BABYLON) {
  40491. var SpotLight = (function (_super) {
  40492. __extends(SpotLight, _super);
  40493. /**
  40494. * Creates a SpotLight object in the scene with the passed parameters :
  40495. * - `position` (Vector3) is the initial SpotLight position,
  40496. * - `direction` (Vector3) is the initial SpotLight direction,
  40497. * - `angle` (float, in radians) is the spot light cone angle,
  40498. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  40499. * A spot light is a simply light oriented cone.
  40500. * It can cast shadows.
  40501. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40502. */
  40503. function SpotLight(name, position, direction, angle, exponent, scene) {
  40504. var _this = _super.call(this, name, scene) || this;
  40505. _this.position = position;
  40506. _this.direction = direction;
  40507. _this.angle = angle;
  40508. _this.exponent = exponent;
  40509. return _this;
  40510. }
  40511. Object.defineProperty(SpotLight.prototype, "angle", {
  40512. get: function () {
  40513. return this._angle;
  40514. },
  40515. set: function (value) {
  40516. this._angle = value;
  40517. this.forceProjectionMatrixCompute();
  40518. },
  40519. enumerable: true,
  40520. configurable: true
  40521. });
  40522. /**
  40523. * Returns the string "SpotLight".
  40524. */
  40525. SpotLight.prototype.getClassName = function () {
  40526. return "SpotLight";
  40527. };
  40528. /**
  40529. * Returns the integer 2.
  40530. */
  40531. SpotLight.prototype.getTypeID = function () {
  40532. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  40533. };
  40534. /**
  40535. * 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.
  40536. * Returns the SpotLight.
  40537. */
  40538. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40539. var activeCamera = this.getScene().activeCamera;
  40540. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  40541. };
  40542. SpotLight.prototype._buildUniformLayout = function () {
  40543. this._uniformBuffer.addUniform("vLightData", 4);
  40544. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40545. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40546. this._uniformBuffer.addUniform("vLightDirection", 3);
  40547. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40548. this._uniformBuffer.create();
  40549. };
  40550. /**
  40551. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  40552. * Return the SpotLight.
  40553. */
  40554. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  40555. var normalizeDirection;
  40556. if (this.computeTransformedInformation()) {
  40557. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  40558. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  40559. }
  40560. else {
  40561. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  40562. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  40563. }
  40564. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  40565. return this;
  40566. };
  40567. return SpotLight;
  40568. }(BABYLON.ShadowLight));
  40569. __decorate([
  40570. BABYLON.serialize()
  40571. ], SpotLight.prototype, "angle", null);
  40572. __decorate([
  40573. BABYLON.serialize()
  40574. ], SpotLight.prototype, "exponent", void 0);
  40575. BABYLON.SpotLight = SpotLight;
  40576. })(BABYLON || (BABYLON = {}));
  40577. //# sourceMappingURL=babylon.spotLight.js.map
  40578. var BABYLON;
  40579. (function (BABYLON) {
  40580. var PostProcess = (function () {
  40581. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  40582. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  40583. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  40584. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  40585. if (blockCompilation === void 0) { blockCompilation = false; }
  40586. this.name = name;
  40587. this.width = -1;
  40588. this.height = -1;
  40589. this.autoClear = true;
  40590. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  40591. /*
  40592. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  40593. Can only be used on a single postprocess or on the last one of a chain.
  40594. */
  40595. this.enablePixelPerfectMode = false;
  40596. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  40597. this.alwaysForcePOT = false;
  40598. this.samples = 1;
  40599. this._reusable = false;
  40600. this._textures = new BABYLON.SmartArray(2);
  40601. this._currentRenderTextureInd = 0;
  40602. this._scaleRatio = new BABYLON.Vector2(1, 1);
  40603. this._texelSize = BABYLON.Vector2.Zero();
  40604. // Events
  40605. /**
  40606. * An event triggered when the postprocess is activated.
  40607. * @type {BABYLON.Observable}
  40608. */
  40609. this.onActivateObservable = new BABYLON.Observable();
  40610. /**
  40611. * An event triggered when the postprocess changes its size.
  40612. * @type {BABYLON.Observable}
  40613. */
  40614. this.onSizeChangedObservable = new BABYLON.Observable();
  40615. /**
  40616. * An event triggered when the postprocess applies its effect.
  40617. * @type {BABYLON.Observable}
  40618. */
  40619. this.onApplyObservable = new BABYLON.Observable();
  40620. /**
  40621. * An event triggered before rendering the postprocess
  40622. * @type {BABYLON.Observable}
  40623. */
  40624. this.onBeforeRenderObservable = new BABYLON.Observable();
  40625. /**
  40626. * An event triggered after rendering the postprocess
  40627. * @type {BABYLON.Observable}
  40628. */
  40629. this.onAfterRenderObservable = new BABYLON.Observable();
  40630. if (camera != null) {
  40631. this._camera = camera;
  40632. this._scene = camera.getScene();
  40633. camera.attachPostProcess(this);
  40634. this._engine = this._scene.getEngine();
  40635. }
  40636. else {
  40637. this._engine = engine;
  40638. }
  40639. this._options = options;
  40640. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  40641. this._reusable = reusable || false;
  40642. this._textureType = textureType;
  40643. this._samplers = samplers || [];
  40644. this._samplers.push("textureSampler");
  40645. this._fragmentUrl = fragmentUrl;
  40646. this._vertexUrl = vertexUrl;
  40647. this._parameters = parameters || [];
  40648. this._parameters.push("scale");
  40649. this._indexParameters = indexParameters;
  40650. if (!blockCompilation) {
  40651. this.updateEffect(defines);
  40652. }
  40653. }
  40654. Object.defineProperty(PostProcess.prototype, "onActivate", {
  40655. set: function (callback) {
  40656. if (this._onActivateObserver) {
  40657. this.onActivateObservable.remove(this._onActivateObserver);
  40658. }
  40659. this._onActivateObserver = this.onActivateObservable.add(callback);
  40660. },
  40661. enumerable: true,
  40662. configurable: true
  40663. });
  40664. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  40665. set: function (callback) {
  40666. if (this._onSizeChangedObserver) {
  40667. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  40668. }
  40669. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  40670. },
  40671. enumerable: true,
  40672. configurable: true
  40673. });
  40674. Object.defineProperty(PostProcess.prototype, "onApply", {
  40675. set: function (callback) {
  40676. if (this._onApplyObserver) {
  40677. this.onApplyObservable.remove(this._onApplyObserver);
  40678. }
  40679. this._onApplyObserver = this.onApplyObservable.add(callback);
  40680. },
  40681. enumerable: true,
  40682. configurable: true
  40683. });
  40684. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  40685. set: function (callback) {
  40686. if (this._onBeforeRenderObserver) {
  40687. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  40688. }
  40689. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  40690. },
  40691. enumerable: true,
  40692. configurable: true
  40693. });
  40694. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  40695. set: function (callback) {
  40696. if (this._onAfterRenderObserver) {
  40697. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  40698. }
  40699. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  40700. },
  40701. enumerable: true,
  40702. configurable: true
  40703. });
  40704. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  40705. get: function () {
  40706. return this._textures.data[this._currentRenderTextureInd];
  40707. },
  40708. enumerable: true,
  40709. configurable: true
  40710. });
  40711. PostProcess.prototype.getCamera = function () {
  40712. return this._camera;
  40713. };
  40714. Object.defineProperty(PostProcess.prototype, "texelSize", {
  40715. get: function () {
  40716. if (this._shareOutputWithPostProcess) {
  40717. return this._shareOutputWithPostProcess.texelSize;
  40718. }
  40719. return this._texelSize;
  40720. },
  40721. enumerable: true,
  40722. configurable: true
  40723. });
  40724. PostProcess.prototype.getEngine = function () {
  40725. return this._engine;
  40726. };
  40727. PostProcess.prototype.shareOutputWith = function (postProcess) {
  40728. this._disposeTextures();
  40729. this._shareOutputWithPostProcess = postProcess;
  40730. return this;
  40731. };
  40732. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters) {
  40733. 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);
  40734. };
  40735. PostProcess.prototype.isReusable = function () {
  40736. return this._reusable;
  40737. };
  40738. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  40739. PostProcess.prototype.markTextureDirty = function () {
  40740. this.width = -1;
  40741. };
  40742. PostProcess.prototype.activate = function (camera, sourceTexture) {
  40743. var _this = this;
  40744. if (!this._shareOutputWithPostProcess) {
  40745. camera = camera || this._camera;
  40746. var scene = camera.getScene();
  40747. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  40748. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  40749. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  40750. var desiredWidth = this._options.width || requiredWidth;
  40751. var desiredHeight = this._options.height || requiredHeight;
  40752. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  40753. if (!this._options.width) {
  40754. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode);
  40755. }
  40756. if (!this._options.height) {
  40757. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode);
  40758. }
  40759. }
  40760. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  40761. if (this._textures.length > 0) {
  40762. for (var i = 0; i < this._textures.length; i++) {
  40763. this._engine._releaseTexture(this._textures.data[i]);
  40764. }
  40765. this._textures.reset();
  40766. }
  40767. this.width = desiredWidth;
  40768. this.height = desiredHeight;
  40769. var textureSize = { width: this.width, height: this.height };
  40770. var textureOptions = {
  40771. generateMipMaps: false,
  40772. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  40773. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  40774. samplingMode: this.renderTargetSamplingMode,
  40775. type: this._textureType
  40776. };
  40777. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  40778. if (this._reusable) {
  40779. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  40780. }
  40781. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  40782. this.onSizeChangedObservable.notifyObservers(this);
  40783. }
  40784. this._textures.forEach(function (texture) {
  40785. if (texture.samples !== _this.samples) {
  40786. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  40787. }
  40788. });
  40789. }
  40790. var target = this._shareOutputWithPostProcess ? this._shareOutputWithPostProcess.outputTexture : this.outputTexture;
  40791. if (this.enablePixelPerfectMode) {
  40792. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  40793. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight);
  40794. }
  40795. else {
  40796. this._scaleRatio.copyFromFloats(1, 1);
  40797. this._engine.bindFramebuffer(target);
  40798. }
  40799. this.onActivateObservable.notifyObservers(camera);
  40800. // Clear
  40801. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  40802. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  40803. }
  40804. if (this._reusable) {
  40805. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  40806. }
  40807. };
  40808. Object.defineProperty(PostProcess.prototype, "isSupported", {
  40809. get: function () {
  40810. return this._effect.isSupported;
  40811. },
  40812. enumerable: true,
  40813. configurable: true
  40814. });
  40815. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  40816. get: function () {
  40817. if (this._shareOutputWithPostProcess) {
  40818. return this._shareOutputWithPostProcess.aspectRatio;
  40819. }
  40820. return this.width / this.height;
  40821. },
  40822. enumerable: true,
  40823. configurable: true
  40824. });
  40825. PostProcess.prototype.apply = function () {
  40826. // Check
  40827. if (!this._effect || !this._effect.isReady())
  40828. return null;
  40829. // States
  40830. this._engine.enableEffect(this._effect);
  40831. this._engine.setState(false);
  40832. this._engine.setDepthBuffer(false);
  40833. this._engine.setDepthWrite(false);
  40834. // Alpha
  40835. this._engine.setAlphaMode(this.alphaMode);
  40836. if (this.alphaConstants) {
  40837. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  40838. }
  40839. // Texture
  40840. var source = this._shareOutputWithPostProcess ? this._shareOutputWithPostProcess.outputTexture : this.outputTexture;
  40841. this._effect._bindTexture("textureSampler", source);
  40842. // Parameters
  40843. this._effect.setVector2("scale", this._scaleRatio);
  40844. this.onApplyObservable.notifyObservers(this._effect);
  40845. return this._effect;
  40846. };
  40847. PostProcess.prototype._disposeTextures = function () {
  40848. if (this._shareOutputWithPostProcess) {
  40849. return;
  40850. }
  40851. if (this._textures.length > 0) {
  40852. for (var i = 0; i < this._textures.length; i++) {
  40853. this._engine._releaseTexture(this._textures.data[i]);
  40854. }
  40855. }
  40856. this._textures.dispose();
  40857. };
  40858. PostProcess.prototype.dispose = function (camera) {
  40859. camera = camera || this._camera;
  40860. this._disposeTextures();
  40861. if (!camera) {
  40862. return;
  40863. }
  40864. camera.detachPostProcess(this);
  40865. var index = camera._postProcesses.indexOf(this);
  40866. if (index === 0 && camera._postProcesses.length > 0) {
  40867. this._camera._postProcesses[0].markTextureDirty();
  40868. }
  40869. this.onActivateObservable.clear();
  40870. this.onAfterRenderObservable.clear();
  40871. this.onApplyObservable.clear();
  40872. this.onBeforeRenderObservable.clear();
  40873. this.onSizeChangedObservable.clear();
  40874. };
  40875. return PostProcess;
  40876. }());
  40877. BABYLON.PostProcess = PostProcess;
  40878. })(BABYLON || (BABYLON = {}));
  40879. //# sourceMappingURL=babylon.postProcess.js.map
  40880. var BABYLON;
  40881. (function (BABYLON) {
  40882. var PassPostProcess = (function (_super) {
  40883. __extends(PassPostProcess, _super);
  40884. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  40885. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  40886. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  40887. }
  40888. return PassPostProcess;
  40889. }(BABYLON.PostProcess));
  40890. BABYLON.PassPostProcess = PassPostProcess;
  40891. })(BABYLON || (BABYLON = {}));
  40892. //# sourceMappingURL=babylon.passPostProcess.js.map
  40893. var BABYLON;
  40894. (function (BABYLON) {
  40895. var BlurPostProcess = (function (_super) {
  40896. __extends(BlurPostProcess, _super);
  40897. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  40898. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  40899. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  40900. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  40901. _this.direction = direction;
  40902. _this.onApplyObservable.add(function (effect) {
  40903. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  40904. });
  40905. _this.kernel = kernel;
  40906. return _this;
  40907. }
  40908. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  40909. /**
  40910. * Gets the length in pixels of the blur sample region
  40911. */
  40912. get: function () {
  40913. return this._idealKernel;
  40914. },
  40915. /**
  40916. * Sets the length in pixels of the blur sample region
  40917. */
  40918. set: function (v) {
  40919. v = Math.max(v, 1);
  40920. this._idealKernel = v;
  40921. this._kernel = this._nearestBestKernel(v);
  40922. this._updateParameters();
  40923. },
  40924. enumerable: true,
  40925. configurable: true
  40926. });
  40927. BlurPostProcess.prototype._updateParameters = function () {
  40928. // Generate sampling offsets and weights
  40929. var N = this._kernel;
  40930. var centerIndex = (N - 1) / 2;
  40931. // Generate Gaussian sampling weights over kernel
  40932. var offsets = [];
  40933. var weights = [];
  40934. var totalWeight = 0;
  40935. for (var i = 0; i < N; i++) {
  40936. var u = i / (N - 1);
  40937. var w = this._gaussianWeight(u * 2.0 - 1);
  40938. offsets[i] = (i - centerIndex);
  40939. weights[i] = w;
  40940. totalWeight += w;
  40941. }
  40942. // Normalize weights
  40943. for (var i = 0; i < weights.length; i++) {
  40944. weights[i] /= totalWeight;
  40945. }
  40946. // Optimize: combine samples to take advantage of hardware linear sampling
  40947. // Walk from left to center, combining pairs (symmetrically)
  40948. var linearSamplingWeights = [];
  40949. var linearSamplingOffsets = [];
  40950. var linearSamplingMap = [];
  40951. for (var i = 0; i <= centerIndex; i += 2) {
  40952. var j = Math.min(i + 1, Math.floor(centerIndex));
  40953. var singleCenterSample = i === j;
  40954. if (singleCenterSample) {
  40955. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  40956. }
  40957. else {
  40958. var sharedCell = j === centerIndex;
  40959. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  40960. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  40961. if (offsetLinear === 0) {
  40962. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  40963. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  40964. }
  40965. else {
  40966. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  40967. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  40968. }
  40969. }
  40970. }
  40971. for (var i = 0; i < linearSamplingMap.length; i++) {
  40972. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  40973. linearSamplingWeights[i] = linearSamplingMap[i].w;
  40974. }
  40975. // Replace with optimized
  40976. offsets = linearSamplingOffsets;
  40977. weights = linearSamplingWeights;
  40978. // Generate shaders
  40979. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  40980. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  40981. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  40982. var defines = "";
  40983. for (var i = 0; i < varyingCount; i++) {
  40984. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  40985. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  40986. }
  40987. var depCount = 0;
  40988. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  40989. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  40990. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  40991. depCount++;
  40992. }
  40993. this._indexParameters.varyingCount = varyingCount;
  40994. this._indexParameters.depCount = depCount;
  40995. this.updateEffect(defines);
  40996. };
  40997. /**
  40998. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  40999. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  41000. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  41001. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  41002. * The gaps between physical kernels are compensated for in the weighting of the samples
  41003. * @param idealKernel Ideal blur kernel.
  41004. * @return Nearest best kernel.
  41005. */
  41006. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  41007. var v = Math.round(idealKernel);
  41008. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  41009. var k = _a[_i];
  41010. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  41011. return Math.max(k, 3);
  41012. }
  41013. }
  41014. return Math.max(v, 3);
  41015. };
  41016. /**
  41017. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  41018. * @param x The point on the Gaussian distribution to sample.
  41019. * @return the value of the Gaussian function at x.
  41020. */
  41021. BlurPostProcess.prototype._gaussianWeight = function (x) {
  41022. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  41023. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  41024. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  41025. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  41026. // truncated at around 1.3% of peak strength.
  41027. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  41028. var sigma = (1 / 3);
  41029. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  41030. var exponent = -((x * x) / (2.0 * sigma * sigma));
  41031. var weight = (1.0 / denominator) * Math.exp(exponent);
  41032. return weight;
  41033. };
  41034. /**
  41035. * Generates a string that can be used as a floating point number in GLSL.
  41036. * @param x Value to print.
  41037. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  41038. * @return GLSL float string.
  41039. */
  41040. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  41041. if (decimalFigures === void 0) { decimalFigures = 8; }
  41042. return x.toFixed(decimalFigures).replace(/0+$/, '');
  41043. };
  41044. return BlurPostProcess;
  41045. }(BABYLON.PostProcess));
  41046. BABYLON.BlurPostProcess = BlurPostProcess;
  41047. })(BABYLON || (BABYLON = {}));
  41048. //# sourceMappingURL=babylon.blurPostProcess.js.map
  41049. var BABYLON;
  41050. (function (BABYLON) {
  41051. var FxaaPostProcess = (function (_super) {
  41052. __extends(FxaaPostProcess, _super);
  41053. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  41054. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41055. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType) || this;
  41056. _this.onApplyObservable.add(function (effect) {
  41057. var texelSize = _this.texelSize;
  41058. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  41059. });
  41060. return _this;
  41061. }
  41062. return FxaaPostProcess;
  41063. }(BABYLON.PostProcess));
  41064. BABYLON.FxaaPostProcess = FxaaPostProcess;
  41065. })(BABYLON || (BABYLON = {}));
  41066. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  41067. var BABYLON;
  41068. (function (BABYLON) {
  41069. var HighlightsPostProcess = (function (_super) {
  41070. __extends(HighlightsPostProcess, _super);
  41071. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  41072. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41073. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  41074. }
  41075. return HighlightsPostProcess;
  41076. }(BABYLON.PostProcess));
  41077. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  41078. })(BABYLON || (BABYLON = {}));
  41079. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  41080. var BABYLON;
  41081. (function (BABYLON) {
  41082. var ImageProcessingPostProcess = (function (_super) {
  41083. __extends(ImageProcessingPostProcess, _super);
  41084. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  41085. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41086. var _this = _super.call(this, name, "imageProcessing", [
  41087. 'contrast',
  41088. 'vignetteSettings1',
  41089. 'vignetteSettings2',
  41090. 'cameraExposureLinear',
  41091. 'vCameraColorCurveNegative',
  41092. 'vCameraColorCurveNeutral',
  41093. 'vCameraColorCurvePositive',
  41094. 'colorTransformSettings'
  41095. ], ["txColorTransform"], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  41096. _this.colorGradingWeight = 1.0;
  41097. _this.colorCurves = new BABYLON.ColorCurves();
  41098. _this.vignetteStretch = 0;
  41099. _this.vignetteCentreX = 0;
  41100. _this.vignetteCentreY = 0;
  41101. _this.vignetteWeight = 1.5;
  41102. _this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  41103. _this._vignetteBlendMode = ImageProcessingPostProcess.VIGNETTEMODE_MULTIPLY;
  41104. _this.cameraContrast = 1.0;
  41105. _this.cameraExposureValue = 1.5;
  41106. _this._cameraToneMappingEnabled = true;
  41107. _this._updateParameters();
  41108. _this.onApply = function (effect) {
  41109. var aspectRatio = _this.aspectRatio;
  41110. // Color
  41111. BABYLON.ColorCurves.Bind(_this.colorCurves, effect);
  41112. // Vignette
  41113. var vignetteScaleY = Math.tan(_this.getCamera().fov * 0.5);
  41114. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41115. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41116. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, _this.vignetteStretch);
  41117. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, _this.vignetteStretch);
  41118. effect.setFloat4('vignetteSettings1', vignetteScaleX, vignetteScaleY, -vignetteScaleX * _this.vignetteCentreX, -vignetteScaleY * _this.vignetteCentreY);
  41119. var vignettePower = -2.0 * _this.vignetteWeight;
  41120. effect.setFloat4('vignetteSettings2', _this.vignetteColor.r, _this.vignetteColor.g, _this.vignetteColor.b, vignettePower);
  41121. // Contrast and exposure
  41122. effect.setFloat('contrast', _this.cameraContrast);
  41123. effect.setFloat('cameraExposureLinear', Math.pow(2.0, -_this.cameraExposureValue) * Math.PI);
  41124. // Color transform settings
  41125. if (_this._colorGradingTexture) {
  41126. effect.setTexture('txColorTransform', _this.colorGradingTexture);
  41127. var textureSize = _this.colorGradingTexture.getSize().height;
  41128. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41129. 0.5 / textureSize, // textureOffset
  41130. textureSize, // textureSize
  41131. _this.colorGradingWeight // weight
  41132. );
  41133. }
  41134. };
  41135. return _this;
  41136. }
  41137. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  41138. get: function () {
  41139. return this._colorGradingTexture;
  41140. },
  41141. set: function (value) {
  41142. if (this._colorGradingTexture === value) {
  41143. return;
  41144. }
  41145. this._colorGradingTexture = value;
  41146. this._updateParameters();
  41147. },
  41148. enumerable: true,
  41149. configurable: true
  41150. });
  41151. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  41152. get: function () {
  41153. return this._vignetteBlendMode;
  41154. },
  41155. set: function (value) {
  41156. if (this._vignetteBlendMode === value) {
  41157. return;
  41158. }
  41159. this._vignetteBlendMode = value;
  41160. this._updateParameters();
  41161. },
  41162. enumerable: true,
  41163. configurable: true
  41164. });
  41165. Object.defineProperty(ImageProcessingPostProcess.prototype, "cameraToneMappingEnabled", {
  41166. get: function () {
  41167. return this._cameraToneMappingEnabled;
  41168. },
  41169. set: function (value) {
  41170. if (this._cameraToneMappingEnabled === value) {
  41171. return;
  41172. }
  41173. this._cameraToneMappingEnabled = value;
  41174. this._updateParameters();
  41175. },
  41176. enumerable: true,
  41177. configurable: true
  41178. });
  41179. ImageProcessingPostProcess.prototype._updateParameters = function () {
  41180. var defines = "";
  41181. var samplers = ["textureSampler"];
  41182. if (this.colorGradingTexture) {
  41183. defines = "#define COLORGRADING\r\n";
  41184. samplers.push("txColorTransform");
  41185. }
  41186. if (this.vignetteBlendMode === ImageProcessingPostProcess._VIGNETTEMODE_MULTIPLY) {
  41187. defines += "#define VIGNETTEBLENDMODEMULTIPLY\r\n";
  41188. }
  41189. else {
  41190. defines += "#define VIGNETTEBLENDMODEOPAQUE\r\n";
  41191. }
  41192. if (this.cameraToneMappingEnabled) {
  41193. defines += "#define TONEMAPPING\r\n";
  41194. }
  41195. this.updateEffect(defines, null, samplers);
  41196. };
  41197. Object.defineProperty(ImageProcessingPostProcess, "VIGNETTEMODE_MULTIPLY", {
  41198. get: function () {
  41199. return ImageProcessingPostProcess._VIGNETTEMODE_MULTIPLY;
  41200. },
  41201. enumerable: true,
  41202. configurable: true
  41203. });
  41204. Object.defineProperty(ImageProcessingPostProcess, "VIGNETTEMODE_OPAQUE", {
  41205. get: function () {
  41206. return ImageProcessingPostProcess._VIGNETTEMODE_OPAQUE;
  41207. },
  41208. enumerable: true,
  41209. configurable: true
  41210. });
  41211. return ImageProcessingPostProcess;
  41212. }(BABYLON.PostProcess));
  41213. // Statics
  41214. ImageProcessingPostProcess._VIGNETTEMODE_MULTIPLY = 0;
  41215. ImageProcessingPostProcess._VIGNETTEMODE_OPAQUE = 1;
  41216. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  41217. })(BABYLON || (BABYLON = {}));
  41218. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  41219. var BABYLON;
  41220. (function (BABYLON) {
  41221. /**
  41222. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41223. * It can help converting any input color in a desired output one. This can then be used to create effects
  41224. * from sepia, black and white to sixties or futuristic rendering...
  41225. *
  41226. * The only supported format is currently 3dl.
  41227. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41228. */
  41229. var ColorGradingTexture = (function (_super) {
  41230. __extends(ColorGradingTexture, _super);
  41231. /**
  41232. * Instantiates a ColorGradingTexture from the following parameters.
  41233. *
  41234. * @param url The location of the color gradind data (currently only supporting 3dl)
  41235. * @param scene The scene the texture will be used in
  41236. */
  41237. function ColorGradingTexture(url, scene) {
  41238. var _this = _super.call(this, scene) || this;
  41239. if (!url) {
  41240. return _this;
  41241. }
  41242. _this._textureMatrix = BABYLON.Matrix.Identity();
  41243. _this.name = url;
  41244. _this.url = url;
  41245. _this.hasAlpha = false;
  41246. _this.isCube = false;
  41247. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41248. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41249. _this.anisotropicFilteringLevel = 1;
  41250. _this._texture = _this._getFromCache(url, true);
  41251. if (!_this._texture) {
  41252. if (!scene.useDelayedTextureLoading) {
  41253. _this.loadTexture();
  41254. }
  41255. else {
  41256. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41257. }
  41258. }
  41259. return _this;
  41260. }
  41261. /**
  41262. * Returns the texture matrix used in most of the material.
  41263. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41264. */
  41265. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41266. return this._textureMatrix;
  41267. };
  41268. /**
  41269. * Occurs when the file being loaded is a .3dl LUT file.
  41270. */
  41271. ColorGradingTexture.prototype.load3dlTexture = function () {
  41272. var _this = this;
  41273. var mipLevels = 0;
  41274. var floatArrayView = null;
  41275. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41276. this._texture = texture;
  41277. var callback = function (text) {
  41278. var data;
  41279. var tempData;
  41280. var line;
  41281. var lines = text.split('\n');
  41282. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41283. var maxColor = 0;
  41284. for (var i = 0; i < lines.length; i++) {
  41285. line = lines[i];
  41286. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41287. continue;
  41288. if (line.indexOf('#') === 0)
  41289. continue;
  41290. var words = line.split(" ");
  41291. if (size === 0) {
  41292. // Number of space + one
  41293. size = words.length;
  41294. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41295. tempData = new Float32Array(size * size * size * 4);
  41296. continue;
  41297. }
  41298. if (size != 0) {
  41299. var r = Math.max(parseInt(words[0]), 0);
  41300. var g = Math.max(parseInt(words[1]), 0);
  41301. var b = Math.max(parseInt(words[2]), 0);
  41302. maxColor = Math.max(r, maxColor);
  41303. maxColor = Math.max(g, maxColor);
  41304. maxColor = Math.max(b, maxColor);
  41305. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41306. tempData[pixelStorageIndex + 0] = r;
  41307. tempData[pixelStorageIndex + 1] = g;
  41308. tempData[pixelStorageIndex + 2] = b;
  41309. tempData[pixelStorageIndex + 3] = 0;
  41310. pixelIndexSlice++;
  41311. if (pixelIndexSlice % size == 0) {
  41312. pixelIndexH++;
  41313. pixelIndexSlice = 0;
  41314. if (pixelIndexH % size == 0) {
  41315. pixelIndexW++;
  41316. pixelIndexH = 0;
  41317. }
  41318. }
  41319. }
  41320. }
  41321. for (var i = 0; i < tempData.length; i++) {
  41322. var value = tempData[i];
  41323. data[i] = (value / maxColor * 255);
  41324. }
  41325. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  41326. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41327. };
  41328. BABYLON.Tools.LoadFile(this.url, callback);
  41329. return this._texture;
  41330. };
  41331. /**
  41332. * Starts the loading process of the texture.
  41333. */
  41334. ColorGradingTexture.prototype.loadTexture = function () {
  41335. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41336. this.load3dlTexture();
  41337. }
  41338. };
  41339. /**
  41340. * Clones the color gradind texture.
  41341. */
  41342. ColorGradingTexture.prototype.clone = function () {
  41343. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41344. // Base texture
  41345. newTexture.level = this.level;
  41346. return newTexture;
  41347. };
  41348. /**
  41349. * Called during delayed load for textures.
  41350. */
  41351. ColorGradingTexture.prototype.delayLoad = function () {
  41352. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41353. return;
  41354. }
  41355. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41356. this._texture = this._getFromCache(this.url, true);
  41357. if (!this._texture) {
  41358. this.loadTexture();
  41359. }
  41360. };
  41361. /**
  41362. * Binds the color grading to the shader.
  41363. * @param colorGrading The texture to bind
  41364. * @param effect The effect to bind to
  41365. */
  41366. ColorGradingTexture.Bind = function (colorGrading, effect) {
  41367. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  41368. var x = colorGrading.level; // Texture Level
  41369. var y = colorGrading.getSize().height; // Texture Size example with 8
  41370. var z = y - 1.0; // SizeMinusOne 8 - 1
  41371. var w = 1 / y; // Space of 1 slice 1 / 8
  41372. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  41373. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  41374. 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
  41375. 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
  41376. 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
  41377. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  41378. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  41379. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  41380. };
  41381. /**
  41382. * Prepare the list of uniforms associated with the ColorGrading effects.
  41383. * @param uniformsList The list of uniforms used in the effect
  41384. * @param samplersList The list of samplers used in the effect
  41385. */
  41386. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  41387. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  41388. samplersList.push("cameraColorGrading2DSampler");
  41389. };
  41390. /**
  41391. * Parses a color grading texture serialized by Babylon.
  41392. * @param parsedTexture The texture information being parsedTexture
  41393. * @param scene The scene to load the texture in
  41394. * @param rootUrl The root url of the data assets to load
  41395. * @return A color gradind texture
  41396. */
  41397. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41398. var texture = null;
  41399. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41400. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  41401. texture.name = parsedTexture.name;
  41402. texture.level = parsedTexture.level;
  41403. }
  41404. return texture;
  41405. };
  41406. /**
  41407. * Serializes the LUT texture to json format.
  41408. */
  41409. ColorGradingTexture.prototype.serialize = function () {
  41410. if (!this.name) {
  41411. return null;
  41412. }
  41413. var serializationObject = {};
  41414. serializationObject.name = this.name;
  41415. serializationObject.level = this.level;
  41416. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41417. return serializationObject;
  41418. };
  41419. return ColorGradingTexture;
  41420. }(BABYLON.BaseTexture));
  41421. /**
  41422. * Empty line regex stored for GC.
  41423. */
  41424. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41425. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41426. })(BABYLON || (BABYLON = {}));
  41427. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41428. var BABYLON;
  41429. (function (BABYLON) {
  41430. /**
  41431. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41432. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41433. * 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;
  41434. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41435. */
  41436. var ColorCurves = (function () {
  41437. function ColorCurves() {
  41438. this._dirty = true;
  41439. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41440. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41441. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41442. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41443. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41444. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41445. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41446. this._globalHue = 30;
  41447. this._globalDensity = 0;
  41448. this._globalSaturation = 0;
  41449. this._globalExposure = 0;
  41450. this._highlightsHue = 30;
  41451. this._highlightsDensity = 0;
  41452. this._highlightsSaturation = 0;
  41453. this._highlightsExposure = 0;
  41454. this._midtonesHue = 30;
  41455. this._midtonesDensity = 0;
  41456. this._midtonesSaturation = 0;
  41457. this._midtonesExposure = 0;
  41458. this._shadowsHue = 30;
  41459. this._shadowsDensity = 0;
  41460. this._shadowsSaturation = 0;
  41461. this._shadowsExposure = 0;
  41462. }
  41463. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41464. /**
  41465. * Gets the global Hue value.
  41466. * 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).
  41467. */
  41468. get: function () {
  41469. return this._globalHue;
  41470. },
  41471. /**
  41472. * Sets the global Hue value.
  41473. * 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).
  41474. */
  41475. set: function (value) {
  41476. this._globalHue = value;
  41477. this._dirty = true;
  41478. },
  41479. enumerable: true,
  41480. configurable: true
  41481. });
  41482. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41483. /**
  41484. * Gets the global Density value.
  41485. * 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.
  41486. * Values less than zero provide a filter of opposite hue.
  41487. */
  41488. get: function () {
  41489. return this._globalDensity;
  41490. },
  41491. /**
  41492. * Sets the global Density value.
  41493. * 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.
  41494. * Values less than zero provide a filter of opposite hue.
  41495. */
  41496. set: function (value) {
  41497. this._globalDensity = value;
  41498. this._dirty = true;
  41499. },
  41500. enumerable: true,
  41501. configurable: true
  41502. });
  41503. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41504. /**
  41505. * Gets the global Saturation value.
  41506. * 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.
  41507. */
  41508. get: function () {
  41509. return this._globalSaturation;
  41510. },
  41511. /**
  41512. * Sets the global Saturation value.
  41513. * 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.
  41514. */
  41515. set: function (value) {
  41516. this._globalSaturation = value;
  41517. this._dirty = true;
  41518. },
  41519. enumerable: true,
  41520. configurable: true
  41521. });
  41522. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41523. /**
  41524. * Gets the highlights Hue value.
  41525. * 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).
  41526. */
  41527. get: function () {
  41528. return this._highlightsHue;
  41529. },
  41530. /**
  41531. * Sets the highlights Hue value.
  41532. * 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).
  41533. */
  41534. set: function (value) {
  41535. this._highlightsHue = value;
  41536. this._dirty = true;
  41537. },
  41538. enumerable: true,
  41539. configurable: true
  41540. });
  41541. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41542. /**
  41543. * Gets the highlights Density value.
  41544. * 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.
  41545. * Values less than zero provide a filter of opposite hue.
  41546. */
  41547. get: function () {
  41548. return this._highlightsDensity;
  41549. },
  41550. /**
  41551. * Sets the highlights Density value.
  41552. * 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.
  41553. * Values less than zero provide a filter of opposite hue.
  41554. */
  41555. set: function (value) {
  41556. this._highlightsDensity = value;
  41557. this._dirty = true;
  41558. },
  41559. enumerable: true,
  41560. configurable: true
  41561. });
  41562. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41563. /**
  41564. * Gets the highlights Saturation value.
  41565. * 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.
  41566. */
  41567. get: function () {
  41568. return this._highlightsSaturation;
  41569. },
  41570. /**
  41571. * Sets the highlights Saturation value.
  41572. * 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.
  41573. */
  41574. set: function (value) {
  41575. this._highlightsSaturation = value;
  41576. this._dirty = true;
  41577. },
  41578. enumerable: true,
  41579. configurable: true
  41580. });
  41581. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41582. /**
  41583. * Gets the highlights Exposure value.
  41584. * 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.
  41585. */
  41586. get: function () {
  41587. return this._highlightsExposure;
  41588. },
  41589. /**
  41590. * Sets the highlights Exposure value.
  41591. * 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.
  41592. */
  41593. set: function (value) {
  41594. this._highlightsExposure = value;
  41595. this._dirty = true;
  41596. },
  41597. enumerable: true,
  41598. configurable: true
  41599. });
  41600. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41601. /**
  41602. * Gets the midtones Hue value.
  41603. * 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).
  41604. */
  41605. get: function () {
  41606. return this._midtonesHue;
  41607. },
  41608. /**
  41609. * Sets the midtones Hue value.
  41610. * 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).
  41611. */
  41612. set: function (value) {
  41613. this._midtonesHue = value;
  41614. this._dirty = true;
  41615. },
  41616. enumerable: true,
  41617. configurable: true
  41618. });
  41619. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41620. /**
  41621. * Gets the midtones Density value.
  41622. * 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.
  41623. * Values less than zero provide a filter of opposite hue.
  41624. */
  41625. get: function () {
  41626. return this._midtonesDensity;
  41627. },
  41628. /**
  41629. * Sets the midtones Density value.
  41630. * 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.
  41631. * Values less than zero provide a filter of opposite hue.
  41632. */
  41633. set: function (value) {
  41634. this._midtonesDensity = value;
  41635. this._dirty = true;
  41636. },
  41637. enumerable: true,
  41638. configurable: true
  41639. });
  41640. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41641. /**
  41642. * Gets the midtones Saturation value.
  41643. * 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.
  41644. */
  41645. get: function () {
  41646. return this._midtonesSaturation;
  41647. },
  41648. /**
  41649. * Sets the midtones Saturation value.
  41650. * 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.
  41651. */
  41652. set: function (value) {
  41653. this._midtonesSaturation = value;
  41654. this._dirty = true;
  41655. },
  41656. enumerable: true,
  41657. configurable: true
  41658. });
  41659. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41660. /**
  41661. * Gets the midtones Exposure value.
  41662. * 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.
  41663. */
  41664. get: function () {
  41665. return this._midtonesExposure;
  41666. },
  41667. /**
  41668. * Sets the midtones Exposure value.
  41669. * 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.
  41670. */
  41671. set: function (value) {
  41672. this._midtonesExposure = value;
  41673. this._dirty = true;
  41674. },
  41675. enumerable: true,
  41676. configurable: true
  41677. });
  41678. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  41679. /**
  41680. * Gets the shadows Hue value.
  41681. * 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).
  41682. */
  41683. get: function () {
  41684. return this._shadowsHue;
  41685. },
  41686. /**
  41687. * Sets the shadows Hue value.
  41688. * 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).
  41689. */
  41690. set: function (value) {
  41691. this._shadowsHue = value;
  41692. this._dirty = true;
  41693. },
  41694. enumerable: true,
  41695. configurable: true
  41696. });
  41697. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  41698. /**
  41699. * Gets the shadows Density value.
  41700. * 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.
  41701. * Values less than zero provide a filter of opposite hue.
  41702. */
  41703. get: function () {
  41704. return this._shadowsDensity;
  41705. },
  41706. /**
  41707. * Sets the shadows Density value.
  41708. * 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.
  41709. * Values less than zero provide a filter of opposite hue.
  41710. */
  41711. set: function (value) {
  41712. this._shadowsDensity = value;
  41713. this._dirty = true;
  41714. },
  41715. enumerable: true,
  41716. configurable: true
  41717. });
  41718. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  41719. /**
  41720. * Gets the shadows Saturation value.
  41721. * 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.
  41722. */
  41723. get: function () {
  41724. return this._shadowsSaturation;
  41725. },
  41726. /**
  41727. * Sets the shadows Saturation value.
  41728. * 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.
  41729. */
  41730. set: function (value) {
  41731. this._shadowsSaturation = value;
  41732. this._dirty = true;
  41733. },
  41734. enumerable: true,
  41735. configurable: true
  41736. });
  41737. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  41738. /**
  41739. * Gets the shadows Exposure value.
  41740. * 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.
  41741. */
  41742. get: function () {
  41743. return this._shadowsExposure;
  41744. },
  41745. /**
  41746. * Sets the shadows Exposure value.
  41747. * 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.
  41748. */
  41749. set: function (value) {
  41750. this._shadowsExposure = value;
  41751. this._dirty = true;
  41752. },
  41753. enumerable: true,
  41754. configurable: true
  41755. });
  41756. /**
  41757. * Binds the color curves to the shader.
  41758. * @param colorCurves The color curve to bind
  41759. * @param effect The effect to bind to
  41760. */
  41761. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  41762. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  41763. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  41764. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  41765. if (colorCurves._dirty) {
  41766. colorCurves._dirty = false;
  41767. // Fill in global info.
  41768. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  41769. // Compute highlights info.
  41770. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  41771. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  41772. // Compute midtones info.
  41773. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  41774. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  41775. // Compute shadows info.
  41776. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  41777. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  41778. // Compute deltas (neutral is midtones).
  41779. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  41780. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  41781. }
  41782. if (effect) {
  41783. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  41784. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  41785. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  41786. }
  41787. };
  41788. /**
  41789. * Prepare the list of uniforms associated with the ColorCurves effects.
  41790. * @param uniformsList The list of uniforms used in the effect
  41791. */
  41792. ColorCurves.PrepareUniforms = function (uniformsList) {
  41793. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  41794. };
  41795. /**
  41796. * Returns color grading data based on a hue, density, saturation and exposure value.
  41797. * @param filterHue The hue of the color filter.
  41798. * @param filterDensity The density of the color filter.
  41799. * @param saturation The saturation.
  41800. * @param exposure The exposure.
  41801. * @param result The result data container.
  41802. */
  41803. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  41804. if (hue == null) {
  41805. return;
  41806. }
  41807. hue = ColorCurves.clamp(hue, 0, 360);
  41808. density = ColorCurves.clamp(density, -100, 100);
  41809. saturation = ColorCurves.clamp(saturation, -100, 100);
  41810. exposure = ColorCurves.clamp(exposure, -100, 100);
  41811. // Remap the slider/config filter density with non-linear mapping and also scale by half
  41812. // so that the maximum filter density is only 50% control. This provides fine control
  41813. // for small values and reasonable range.
  41814. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  41815. density *= 0.5;
  41816. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  41817. if (density < 0) {
  41818. density *= -1;
  41819. hue = (hue + 180) % 360;
  41820. }
  41821. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  41822. result.scaleToRef(2, result);
  41823. result.a = 1 + 0.01 * saturation;
  41824. };
  41825. /**
  41826. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  41827. * @param value The input slider value in range [-100,100].
  41828. * @returns Adjusted value.
  41829. */
  41830. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  41831. value /= 100;
  41832. var x = Math.abs(value);
  41833. x = Math.pow(x, 2);
  41834. if (value < 0) {
  41835. x *= -1;
  41836. }
  41837. x *= 100;
  41838. return x;
  41839. };
  41840. /**
  41841. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  41842. * @param hue The hue (H) input.
  41843. * @param saturation The saturation (S) input.
  41844. * @param brightness The brightness (B) input.
  41845. * @result An RGBA color represented as Vector4.
  41846. */
  41847. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  41848. var h = ColorCurves.clamp(hue, 0, 360);
  41849. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  41850. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  41851. if (s === 0) {
  41852. result.r = v;
  41853. result.g = v;
  41854. result.b = v;
  41855. }
  41856. else {
  41857. // sector 0 to 5
  41858. h /= 60;
  41859. var i = Math.floor(h);
  41860. // fractional part of h
  41861. var f = h - i;
  41862. var p = v * (1 - s);
  41863. var q = v * (1 - s * f);
  41864. var t = v * (1 - s * (1 - f));
  41865. switch (i) {
  41866. case 0:
  41867. result.r = v;
  41868. result.g = t;
  41869. result.b = p;
  41870. break;
  41871. case 1:
  41872. result.r = q;
  41873. result.g = v;
  41874. result.b = p;
  41875. break;
  41876. case 2:
  41877. result.r = p;
  41878. result.g = v;
  41879. result.b = t;
  41880. break;
  41881. case 3:
  41882. result.r = p;
  41883. result.g = q;
  41884. result.b = v;
  41885. break;
  41886. case 4:
  41887. result.r = t;
  41888. result.g = p;
  41889. result.b = v;
  41890. break;
  41891. default:
  41892. result.r = v;
  41893. result.g = p;
  41894. result.b = q;
  41895. break;
  41896. }
  41897. }
  41898. result.a = 1;
  41899. };
  41900. /**
  41901. * Returns a value clamped between min and max
  41902. * @param value The value to clamp
  41903. * @param min The minimum of value
  41904. * @param max The maximum of value
  41905. * @returns The clamped value.
  41906. */
  41907. ColorCurves.clamp = function (value, min, max) {
  41908. return Math.min(Math.max(value, min), max);
  41909. };
  41910. /**
  41911. * Clones the current color curve instance.
  41912. * @return The cloned curves
  41913. */
  41914. ColorCurves.prototype.clone = function () {
  41915. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  41916. };
  41917. /**
  41918. * Serializes the current color curve instance to a json representation.
  41919. * @return a JSON representation
  41920. */
  41921. ColorCurves.prototype.serialize = function () {
  41922. return BABYLON.SerializationHelper.Serialize(this);
  41923. };
  41924. /**
  41925. * Parses the color curve from a json representation.
  41926. * @param source the JSON source to parse
  41927. * @return The parsed curves
  41928. */
  41929. ColorCurves.Parse = function (source) {
  41930. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  41931. };
  41932. return ColorCurves;
  41933. }());
  41934. __decorate([
  41935. BABYLON.serialize()
  41936. ], ColorCurves.prototype, "_globalHue", void 0);
  41937. __decorate([
  41938. BABYLON.serialize()
  41939. ], ColorCurves.prototype, "_globalDensity", void 0);
  41940. __decorate([
  41941. BABYLON.serialize()
  41942. ], ColorCurves.prototype, "_globalSaturation", void 0);
  41943. __decorate([
  41944. BABYLON.serialize()
  41945. ], ColorCurves.prototype, "_globalExposure", void 0);
  41946. __decorate([
  41947. BABYLON.serialize()
  41948. ], ColorCurves.prototype, "_highlightsHue", void 0);
  41949. __decorate([
  41950. BABYLON.serialize()
  41951. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  41952. __decorate([
  41953. BABYLON.serialize()
  41954. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  41955. __decorate([
  41956. BABYLON.serialize()
  41957. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  41958. __decorate([
  41959. BABYLON.serialize()
  41960. ], ColorCurves.prototype, "_midtonesHue", void 0);
  41961. __decorate([
  41962. BABYLON.serialize()
  41963. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  41964. __decorate([
  41965. BABYLON.serialize()
  41966. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  41967. __decorate([
  41968. BABYLON.serialize()
  41969. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  41970. BABYLON.ColorCurves = ColorCurves;
  41971. })(BABYLON || (BABYLON = {}));
  41972. //# sourceMappingURL=babylon.colorCurves.js.map
  41973. BABYLON.Effect.ShadersStore={"colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","defaultVertexShader":"#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","defaultPixelShader":"#include<__decl__defaultFragment>\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition> \n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#include<colorCurves>\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n#ifdef CAMERACOLORGRADING\ncolor=colorGrades(color);\n#endif\n#ifdef CAMERACOLORCURVES\ncolor.rgb=applyColorCurves(color.rgb);\n#endif\ngl_FragColor=color;\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\n#endif\n#ifdef MICROSURFACEMAP\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef MICROSURFACEMAP\nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP)|| !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\nvarying vec2 vMicroSurfaceSamplerUV;\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#endif\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#ifdef CAMERACOLORGRADING\n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurves>\n#endif\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<helperFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL) \nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#ifdef ALPHAFROMALBEDO\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#if defined(ALPHATEST) && defined(ALPHATESTVALUE)\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef METALLICMAP\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nfloat NdotL=-1.;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\n\n\nfloat reflectance90=clamp(reflectance*25.0,0.0,1.0);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nlightingInfo info;\nfloat shadow=1.; \n#include<lightFragment>[0..maxSimultaneousLights]\nvec3 lightDiffuseContribution=diffuseBase;\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=specularBase*vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif ((vMicrosurfaceTextureLods.y-lodRefraction)>4.0)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif ((vMicrosurfaceTextureLods.y-lodReflection)>4.0)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0,0.0,0.0);\n#ifdef REFRACTION\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nsurfaceRefractionColor*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=surfaceRefractionColor*transmission;\n#endif\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\nvec3 finalDiffuse=lightDiffuseContribution;\n#ifndef EMISSIVEASILLUMINATION\nfinalDiffuse+=surfaceEmissiveColor;\n#endif\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\nfinalDiffuse=(finalDiffuse*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance)*ambientOcclusionColor;\nfloat luminanceOverAlpha=0.0;\n#ifdef RADIANCEOVERALPHA\nluminanceOverAlpha+=getLuminance(environmentRadiance);\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#ifdef SPECULAROVERALPHA\nluminanceOverAlpha+=getLuminance(finalSpecular);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nfinalSpecular*=vLightingIntensity.x;\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*alpha,0.,1.);\n#endif\n\n\nvec4 finalColor=vec4(finalDiffuse+finalSpecular+environmentRadiance+refractance,alpha);\n#ifdef EMISSIVEASILLUMINATION\nfinalColor.rgb+=(surfaceEmissiveColor*vLightingIntensity.y);\n#endif\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\n#ifdef LDROUTPUT\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\n#endif\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nvoid main(void)\n{\nvec4 blend=vec4(0.);\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\ngl_FragColor=blend;\n}","fxaaPixelShader":"varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\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 sampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nvec2 sampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nvec2 sampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nvec2 sampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nvec2 sampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nvec2 sampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nvec2 sampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nvec2 sampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\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 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){\nresult.rgb*=cameraExposureLinear;\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#ifdef TONEMAPPING \nfloat tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\nresult.rgb=pow(result.rgb,vec3(GammaEncodePowerApprox));\nresult.rgb=clamp(result.rgb,0.0,1.0);\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\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);\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}"};
  41974. BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if !defined(SHADOWCUBE{X})\nuniform mat4 lightMatrix{X};\nvarying vec4 vPositionFromLight{X};\n#endif\n#endif\n","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 normalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\nvec3 tangentW=normalize(vec3(finalWorld*vec4(tangentUpdated.xyz,0.0)));\nvec3 bitangentW=cross(normalW,tangentW)*tangentUpdated.w;\nvTBN=mat3(tangentW,bitangentW,normalW);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"mat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#endif\nuniform vec3 shadowsInfo{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec3 shadowsInfo;\n} light{X};\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample-darkness,0.,1.); \nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (depth.z>shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<depth.z) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<depth.z) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<depth.z) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<depth.z) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<depth.z) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<depth.z) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<depth.z) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<depth.z) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float depthScale)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 depth=0.5*clipSpace+vec3(0.5);\nvec2 uv=depth.xy;\nfloat shadowPixelDepth=depth.z;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample-darkness,0.,1.); \n\n\n\n\n\nreturn esm;\n}\n#endif","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","colorGradingDefinition":"uniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;","colorGrading":"vec4 colorGrades(vec4 color) \n{ \n\nfloat sliceContinuous=color.z*vCameraColorGradingInfos.z;\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger; \n\nvec2 sliceUV=color.xy*vCameraColorGradingScaleOffset.xy+vCameraColorGradingScaleOffset.zw;\n\n\nsliceUV.x+=sliceInteger*vCameraColorGradingInfos.w;\nvec4 slice0Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nsliceUV.x+=vCameraColorGradingInfos.w;\nvec4 slice1Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=mix(color.rgb,result,vCameraColorGradingInfos.x);\nreturn color;\n}","colorCurvesDefinition":"uniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform vec4 vCameraColorCurveNegative;","colorCurves":"const vec3 HDTVRec709_RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvec3 applyColorCurves(vec3 original) {\nvec3 result=original;\n\n\n\nfloat luma=dot(result.rgb,HDTVRec709_RGBLuminanceCoefficients);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0,0.0),vec2(1.0,1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma,luma,luma),result.rgb,colorCurve.a);\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n#ifdef USERIGHTHANDEDSYSTEM\nbinormal=-binormal;\n#endif\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\n#ifdef INVERTNORMALMAPX\nmap.x=1.0-map.x;\n#endif\n#ifdef INVERTNORMALMAPY\nmap.y=1.0-map.y;\n#endif\nmap=map*255./127.-128./127.;\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nnormalW=normalize(normalW*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},light{X}.shadowsInfo.x);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\n#else\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec2 vMicrosurfaceTextureLods;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform vec4 opacityParts;\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kPi=3.1415926535897932384626433832795;\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat Square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,vec3(0.2126,0.7152,0.0722)),0.,1.);\n}\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=Square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat getMipMapIndexFromAverageSlope(float maxMipLevel,float alpha)\n{\n\n\n\n\n\n\n\nfloat mip=kRougnhessToAlphaOffset+maxMipLevel+(maxMipLevel*kRougnhessToAlphaScale*log2(alpha));\nreturn clamp(mip,0.,maxMipLevel);\n}\nfloat getMipMapIndexFromAverageSlopeWithPMREM(float maxMipLevel,float alphaG)\n{\nfloat specularPower=clamp(2./alphaG-2.,0.000001,2048.);\n\nreturn clamp(- 0.5*log2(specularPower)+5.5,0.,maxMipLevel);\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=Square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(kPi*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 FresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 specularColor,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nvec3 fresnel=fresnelSchlickGGX(VdotH,specularColor,reflectance90);\nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nreturn fresnel*specTerm*kPi; \n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat diffuseFresnelTerm =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn diffuseFresnelTerm*NdotL;\n\n\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nfloat kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn vec3(pow(color.r,2.2),pow(color.g,2.2),pow(color.b,2.2));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn vec3(pow(color.r,1.0/2.2),pow(color.g,1.0/2.2),pow(color.b,1.0/2.2));\n}\n#ifdef CAMERATONEMAP\nvec3 toneMaps(vec3 color)\n{\ncolor=max(color,0.0);\n\ncolor.rgb=color.rgb*vCameraInfos.x;\nfloat tuning=1.5; \n\n\nvec3 tonemapped=1.0-exp2(-color.rgb*tuning); \ncolor.rgb=mix(color.rgb,tonemapped,1.0);\nreturn color;\n}\n#endif\n#ifdef CAMERACONTRAST\nvec4 contrasts(vec4 color)\n{\ncolor=clamp(color,0.0,1.0);\nvec3 resultHighContrast=color.rgb*color.rgb*(3.0-2.0*color.rgb);\nfloat contrast=vCameraInfos.y;\nif (contrast<1.0)\n{\n\ncolor.rgb=mix(vec3(0.5,0.5,0.5),color.rgb,contrast);\n}\nelse\n{\n\ncolor.rgb=mix(color.rgb,resultHighContrast,contrast-1.0);\n}\nreturn color;\n}\n#endif","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX;\nuniform vec3 vSphericalYY;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 EnvironmentIrradiance(vec3 normal)\n{\n\n\n\nvec3 result =\nvSphericalX*normal.x +\nvSphericalY*normal.y +\nvSphericalZ*normal.z +\nvSphericalXX*normal.x*normal.x +\nvSphericalYY*normal.y*normal.y +\nvSphericalZZ*normal.z*normal.z +\nvSphericalYZ*normal.y*normal.z +\nvSphericalZX*normal.z*normal.x +\nvSphericalXY*normal.x*normal.y;\nreturn result.rgb;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.0001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat cosHalfAngle=cos(lightAngle*0.5);\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=lightAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=max(0.00000000001,dot(vNormal,lightDirection));\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=max(0.00000000001,dot(vNormal,directionToLightCenterW));\nfloat VdotH=clamp(dot(viewDirectionW,H),0.00000000001,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nNdotL=max(0.00000000001,NdotL);\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm;\n#endif\nreturn result;\n}","kernelBlurFragment":"blend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n","kernelBlurFragment2":"blend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\n","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};"};
  41975. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  41976. module.exports = BABYLON;
  41977. };